繁体   English   中英

查找列表中的元素并输出子列表项

[英]Finding element within lists and output the sublist item

我遇到的问题包括搜索子列表中的特定值,并仅在列表中输出所需的子列表。

该代码将有助于理解我的问题:

list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"', '1']]
list2 = [['4', '"id8"', '1'],['6', '"id8"', '1'],['12', '"id8"', '1']]

list1_first = [int(item[0]) for item in list1]
list2_first = [int(item[0]) for item in list2]

compare = set(list1_first) & set(list2_first)

print(list1_first) # outputs: [12, 14, 16]
print(list2_first) # outputs: [4, 6, 12]
print(compare) # outputs: {12}

# find the compared value within list 1 and list 2
largelist = list1 + list2
print(largelist) # outputs: [['12', '"id1"', '1'], ['14', '"id1"', '1'], ['16', '"id1"', '1'], ['4', '"id8"', '1'], ['6', '"id8"', '1'], ['12', '"id8"', '1']]

for item in largelist:
    if compare in list1:
        print('Found:',item) # does not print anything
        # wanted output: Found: ['12', '"id1"', '1'], Found ['12', '"id8"', '1']

我的代码没有打印任何内容,我认为这是基于每个列表中的第一个数字未注释为整数的事实? 你知道为什么这不起作用,我怎么能解决它?

您正在将集合{12}list1每个子列表进行比较,您需要查看每个子列表中的任何元素是否在集合中。

不完全确定你想要什么,但这可能更接近:

list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"',     

list1_first = [(item[0]) for item in list1]

compare = set(list1_first).intersection(ele[0] for ele in list2)

from itertools import chain

for item in chain(list1,list2):
    if compare.issubset(item):
        print('Found:',item)

哪个输出:

Found: ['12', '"id1"', '1']
Found: ['12', '"id8"', '1']

你可以散列一个字符串,这样就完全没有意义了。

您还可以使用dict和filter对列表进行一次传递:

list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"', '1']]
list2 = [['4', '"id8"', '1'],['6', '"id8"', '1'],['12', '"id8"', '1']]


from itertools import chain
from collections import defaultdict
d = defaultdict(list)
for item in chain(list1,list2):
    d[item[0]].append(item)


print(list(filter(lambda x: len(x)> 1, d.values())))

您的代码不会打印任何内容,因为

if compare in list1:

compare是一个集合, list1不包含任何集合。

如果{12} (仅包含数字12的集合)在list1 ,则代码将打印largelist所有项目。 如果要打印其编号在两个列表中的项目,可以使用以下命令:

for item in largelist:
    if int(item[0]) in compare:
        print('Found:', item)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM