gpt4 book ai didi

python - 将元组的成员与列表的成员匹配,python

转载 作者:行者123 更新时间:2023-12-01 06:03:19 25 4
gpt4 key购买 nike

我原以为这会是相当微不足道的事情,但事实证明它比我预期的要困难。

我有一个元组列表:

  tuples = [('apples', 2, 'apple'), ('oranges', 3, 'orange')]

我有包含元组列表中元组的可能成员的行列表:

 list_of_lines = ['banana 1234', 'apple 5678', 'oranges 4321','apples 8765', 'orange 1111')]

对于元组中的 tuple[0] 和 tuple[2],我需要匹配 list_of_lines 中第一个位置的成员并获取该成员的值(第二个位置)。关键是将这些结果输出在一行上。例如,对于元组中的第一个元组,所需的输出将是:

 'apples', 8765, 2, 'apple',5678

即元组的原始成员,现在具有与 list_of_lines 匹配的值。

如果我们尝试这样做

  for tup in tuples:
for line in list_of_lines:
if tuple[0] == line.split()[0]:
print tuple[0], line.split()[1]
if tuple[2] == line.split()[0]:
print tuple[2], line.split()[1]

那么一行上什么都没有,我们会得到重复的匹配。

最佳答案

如果您先将 list_of_lines 转换为字典,会更容易。

>>> tuples = [('apples', 2, 'apple'), ('oranges', 3, 'orange')]
>>> list_of_lines = ['banana 1234', 'apple 5678',
... 'oranges 4321','apples 8765']
>>> line_no = dict(x.split() for x in list_of_lines)
>>> result = [(x[0], line_no.get(x[0], None), x[1],
x[2], line_no.get(x[2], None)) for x in tuples]
>>> result
[('apples', '8765', 2, 'apple', '5678'), ('oranges', '4321', 3, 'orange', None)]

关于python - 将元组的成员与列表的成员匹配,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com