我有两个清单:
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])
但我得到一个“字符串索引超出范围错误”
使用列表理解可以轻松完成输出:
LC替代方案:
^{pr2}$如果需要循环结构:
Python序列通常不需要枚举来处理序列中的对象。通常情况下,除了序列本身之外,如果索引或顺序还有“data”的地方,则只需要使用
enumerate
。在这里您将获取}。您的输出是
wordlist_compound
中的每个元素,并测试wordlist
中单词的成员资格。不需要枚举。如果反向循环,也可以大大简化任务;循环wordlist_compound
,而不是在外部循环中循环{wordlist_compound
中元素的过滤器;当然,这意味着您也可以使用filter
:干杯。在
问题是}会产生索引越界错误。在
len(wordlist) > len(wordlist_compound)
,所以使用wordlist
的index
来索引{另外,正如@aga所提到的,应该是
if word == wordlist_compound[index][0]
。在我相信这是必须的
^{pr2}$在元素}不存在。在
'Aaru'
上得到了这个异常:它的索引是7
,而{但这个观察结果不会对您有所帮助,因为您的循环包含一些逻辑错误。我会这样改写:
或者使用列表理解,如dawg have shown。在
相关问题 更多 >
编程相关推荐