问题:在元组列表中查找元素
我有一个清单“ a”
a= [(1,2),(1,4),(3,5),(5,7)]我需要找到一个特定数字的所有元组。说1
result = [(1,2),(1,4)]我怎么做?
回答 0
如果只希望第一个数字匹配,则可以这样操作:
[item for item in a if item[0] == 1]如果您仅搜索其中包含1的元组:
[item for item in a if 1 in item]回答 1
实际上,有一种聪明的方法可以用于任何元组列表,其中每个元组的大小为2:您可以将列表转换成一个字典。
例如,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1回答 2
阅读列表理解
[ (x,y) for x, y in a if x  == 1 ]还要阅读生成器函数和yield语句。
def filter_value( someList, value ):
    for x, y in someList:
        if x == value :
            yield x,y
result= list( filter_value( a, 1 ) )回答 3
[tup for tup in a if tup[0] == 1]回答 4
for item in a:
   if 1 in item:
       print item回答 5
>>> [i for i in a if 1 in i][(1,2),(1,4)]
回答 6
该filter函数还可以提供一个有趣的解决方案:
result = list(filter(lambda x: x.count(1) > 0, a))它会在列表中的元组中搜索是否出现1。如果搜索仅限于第一个元素,则可以将解决方案修改为:
result = list(filter(lambda x: x[0] == 1, a))回答 7
使用过滤功能:
>>> def get_values(iterables,key_to_find):
返回列表(过滤器(lambda x:x中的key_to_find,可迭代)) >>> a = [(1,2 ,,(1,4),(3,5),(5,7)] >>> get_values(a,1) >>> [(1,2),(1,4)]
回答 8
或takewhile,(此外,还会显示更多值的示例):
>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 如果未排序,例如:
>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 回答 9
如果要在元组中搜索元组中存在的任何数字,则可以使用
a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)
print(result)if i==j[0] or i==j[index]如果要搜索特定索引中的数字,也可以使用
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

