我有两个清单:
wordlist = ['A', 'Aani', 'Aaron', 'Aaronic',
'Aaronical', 'Aaronite', 'Aaronitic',
'Aaru', 'Ab', 'Ababdeh']
和
wordlist_compound = [['A','0'], ['Aaronic','1'], ['Key','2'],
['Aaronical','3'], ['Aaronite','4'], ['Yes','5']]
我想取两个单词的交集,并在第三个列表中创建一个包含单词,数字组合编号的列表wordlist_final,以便wordlist_final看起来像:
[['A','0'], ['Aaronic','1'], ['Aaronical','3'], ['Aaronite','4']]
我目前的代码如下:
wordlist_final = []
for index, word in enumerate(wordlist):
for word_comp in wordlist_compound:
if word[index] == wordlist_compound[index][0]:
wordlist_final.append(wordlist_compound[index])
但我得到一个“字符串索引超出范围错误”
解决方法:
使用列表推导可以轻松完成输出:
wl=['A', 'Aani', 'Aaron', 'Aaronic', 'Aaronical', 'Aaronite', 'Aaronitic', 'Aaru', 'Ab', 'Ababdeh']
wlc=[['A','0'], ['Aaronic','1'], ['Key','2'], ['Aaronical','3'], ['Aaronite','4'], ['Yes','5']]
print [[word, i] for word,i in wlc if word in wl]
# [['A', '0'], ['Aaronic', '1'], ['Aaronical', '3'], ['Aaronite', '4']]
替代LC:
print [li for li in wlc if li[0] in wl]
如果你想要一个循环结构:
wlf = []
for word, i in wlc:
if word in wl:
wlf.append([word,i])
print wlf
# [['A', '0'], ['Aaronic', '1'], ['Aaronical', '3'], ['Aaronite', '4']]
Python序列通常不需要枚举来处理序列中的对象.如果除了序列本身之外还有关于索引或顺序的“数据”,您通常只需要使用枚举.
在这里,您将获取wordlist_compound中的每个元素,并测试wordlist中单词的成员身份.无需枚举.如果颠倒循环,也可以大大简化任务;循环使用wordlist_compound而不是循环遍历外部循环中的wordlist.您的输出是wordlist_compound中元素的过滤器;当然,这意味着您也可以使用过滤器:
print filter(lambda li: li[0] in wl, wlc)
# [['A', '0'], ['Aaronic', '1'], ['Aaronical', '3'], ['Aaronite', '4']]
干杯.