【发布时间】:2018-05-10 07:35:44
【问题描述】:
我有一个这样的嵌套列表:
lst = [['one two', 'three', '10'], ['spam eggs', 'spam', '8'],
['two three', 'four', '5'], ['foo bar', 'foo', '7'],
['three four', 'five', '9']]
最后一个元素是一种概率。 我需要的是找到元素,其中一个元素的第二个和第三个单词匹配另一个元素的第一个和第二个单词,例如:
['one two', 'three', '10'] match ['two three', 'four', '5'] match ['three four', 'five', '9']
并制作如下链:
one two 10 three 5 four 9 five
我知道第一步必须是元素的标记化:
lst = ([' '.join(x).split() for x in lst])
for i in lst:
print(i)
所以我明白了
['one', 'two', 'three', '10']
['spam', 'eggs', 'spam', '8']
['two', 'three', 'four', '4']
['foo', 'bar', 'foo', '7']
['three', 'four', 'five', '9']
下一步应该是对列表的每个元素进行某种迭代搜索,但我对这种搜索的 Python 实现有点卡住了。 任何帮助,将不胜感激。
【问题讨论】:
-
您需要得到什么结果?要遍历列表中的项目,请使用
for循环:for item in list: -
@Konstantin 感谢您的回复!正如我所写的,作为最终结果,我需要像“一二十三五四九五”这样的链,但即使你会帮助迭代搜索列表中的一对元素,它也会很好。
标签: python python-3.x list search