如果条件为真,则创建具有相邻列表元素的元组列表 [英] Create a list of tuples with adjacent list elements if a condition is true

查看:89
本文介绍了如果条件为真,则创建具有相邻列表元素的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个元组列表,其中元组内容是数字9和列表中之前的数字.

I am trying to create a list of tuples where the tuple contents are the number 9 and the number before it in the list.

输入列表:

myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]

所需的输出:

sets = [(8, 9), (4, 9), (7, 9)]

代码:

sets = [list(zip(myList[i:i], myList[-1:])) for i in myList if i==9]

当前结果:

[[], [], []]

推荐答案

更干净的Python方法:

Cleaner Pythonic approach:

>>> [(x,y) for x,y in zip(myList, myList[1:]) if y == 9]
[(8, 9), (4, 9), (7, 9)]


上面的代码是做什么的


What is the code above doing:

  • zip(some_list, some_list[1:])会生成一对相邻元素的列表.
  • 现在有了该元组,请在第二个元素等于9的条件下进行过滤.您完成了:)
  • zip(some_list, some_list[1:]) would generate a list of pairs of adjacent elements.
  • Now with that tuple, filter on the condition that the second element is equal to 9. You're done :)

这篇关于如果条件为真,则创建具有相邻列表元素的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆