Bru*_*uce 123 python search tuples list
我有一个列表'a'
a= [(1,2),(1,4),(3,5),(5,7)]
Run Code Online (Sandbox Code Playgroud)
我需要找到特定数字的所有元组.说它会是1
result = [(1,2),(1,4)]
Run Code Online (Sandbox Code Playgroud)
我怎么做?
Nad*_*mli 210
如果你只想让第一个数字匹配,你可以这样做:
[item for item in a if item[0] == 1]
Run Code Online (Sandbox Code Playgroud)
如果您只是搜索其中包含1的元组:
[item for item in a if 1 in item]
Run Code Online (Sandbox Code Playgroud)
小智 104
实际上有一种聪明的方法可以用于任何元组列表,每个元组的大小为2:您可以将列表转换为单个字典.
例如,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
Run Code Online (Sandbox Code Playgroud)
S.L*_*ott 20
阅读列表理解
[ (x,y) for x, y in a if x == 1 ]
Run Code Online (Sandbox Code Playgroud)
还读取了生成器函数和yield语句.
def filter_value( someList, value ):
for x, y in someList:
if x == value :
yield x,y
result= list( filter_value( a, 1 ) )
Run Code Online (Sandbox Code Playgroud)
该filter函数还可以提供一个有趣的解决方案:
result = list(filter(lambda x: x.count(1) > 0, a))
Run Code Online (Sandbox Code Playgroud)
它在列表中的元组中搜索a任何出现的1. 如果搜索仅限于第一个元素,则解决方案可以修改为:
result = list(filter(lambda x: x[0] == 1, a))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
299325 次 |
| 最近记录: |