列表和列表列表的第一个元素之间的交集

2024-09-28 22:39:28 发布

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

我有两个清单:

wordlist =  ['A', 'Aani', 'Aaron', 'Aaronic',
             'Aaronical', 'Aaronite', 'Aaronitic',
             'Aaru', 'Ab', 'Ababdeh']

以及

^{pr2}$

我想取这两个单词的交集,列一个包含单词的列表,第三个列表中的数字组合数字,wordlist_final,这样wordlist_final看起来像:

^{3}$

我当前的代码如下:

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])

但我得到一个“字符串索引超出范围错误”


Tags: in列表forindex数字单词wordfinal
3条回答

使用列表理解可以轻松完成输出:

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替代方案:

^{pr2}$

如果需要循环结构:

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序列通常不需要枚举来处理序列中的对象。通常情况下,除了序列本身之外,如果索引或顺序还有“data”的地方,则只需要使用enumerate。在

这里您将获取wordlist_compound中的每个元素,并测试wordlist中单词的成员资格。不需要枚举。如果反向循环,也可以大大简化任务;循环wordlist_compound,而不是在外部循环中循环{}。您的输出是wordlist_compound中元素的过滤器;当然,这意味着您也可以使用filter

print filter(lambda li: li[0] in wl, wlc)
# [['A', '0'], ['Aaronic', '1'], ['Aaronical', '3'], ['Aaronite', '4']]

干杯。在

问题是len(wordlist) > len(wordlist_compound),所以使用wordlistindex来索引{}会产生索引越界错误。在

另外,正如@aga所提到的,应该是if word == wordlist_compound[index][0]。在

if word[index] == wordlist_compound[index][0]:

我相信这是必须的

^{pr2}$

在元素'Aaru'上得到了这个异常:它的索引是7,而{}不存在。在

但这个观察结果不会对您有所帮助,因为您的循环包含一些逻辑错误。我会这样改写:

for inner_list in wordlist_compound: 
    if inner_list[0] in wordlist: 
        wordlist_final.append(inner_list) 

或者使用列表理解,如dawg have shown。在

相关问题 更多 >