拿两张单子比较相似之处

2024-04-25 21:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个清单如下:

sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]

我需要创建一个for循环来查看sq中有多少元素包含在sl的子列表中。如果sq中的一个词包含在sl中,它将添加1作为匹配项,如果不匹配,则添加0

因此,作为上面列表中的一个示例,我们采用sl的第一个子列表,即:

['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did']

并将其与qs列表进行比较,以查看子列表中是否包含qs中的任何内容。结果应该是这样一个列表:

[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0]

第一个子列表中有11个单词,这就是我希望在列表中显示匹配项的方式。我需要为sl中的每个子列表执行此操作。下面是我的当前代码,这是一个很大的偏差。你知道吗

testList = []
testlistnew =[]
for k in sl:
    if k not in testlistnew:
        testlistnew[k] = 0
    if k in sq:
        testList[k] = 1
    else:
        testList[k] = 0

仅供参考,这应该是整个sq与sl比较的输出:

matches = [[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1, 0, 0]]

Tags: thetoin列表sqdoarewe
2条回答

这里有一个方法。sum正在压平嵌套列表。你知道吗

sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]

_flat = sum(sq, [])
test = []

for i, nested_list in enumerate(sl):
    test.append([])
    for item in nested_list:
        test[i].append(1 if item in _flat else 0)
print(test)

Forloop可能有助于更多的理解,但这可以通过使用列表理解更简洁地完成。或者,看评论。你知道吗

sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]
_flat = sum(sq, [])
test = [[1 if item in _flat else 0 for item in nl] for nl in sl]

另一种选择。你知道吗

注意事项:

  • 比起for循环,我更喜欢列表理解。

  • 我将所有要匹配的数据放在set中以加快查找速度。

你知道吗

from pprint import pprint

# Test data
sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]

# Create result
sq_set = set(sq_str for sq_item in sq for sq_str in sq_item)
result =  [
    [
        int(sl_str in sq_set)
        for sl_str in sl_item
    ]
    for sl_item in sl
]

# Display result
pprint (result)

相关问题 更多 >