我有一个包含子列表的列表,每个子列表包含2个字符串:
cor = [['s', 'urmange'], ['su', 'rmange'], ['sur', 'mange'], ['surm', 'ange'], ['surma', 'nge'], ['surman', 'ge'], ['surmang', 'e']]
现在我想检查子列表中的每两个元素,如果它存在于一个名为dic的字典中,如果这两个元素存在if subL[1] in Dic and subL[2] in Dic:
,我将得到如下输出:
sur mange
否则print("No match with dic")
如何使用Python实现这一点?你知道吗
这就是我一直在做的:
for sub_list in cor:
for i in range (0,len(sub_list)):
if sub_list[i] in my_list and sub_list[i+1] in my_list:
print ("R3: You mean:", sub_list)
我得到下一个输出:
R3: You mean: ['sur', 'mange']
出现此错误时:
Traceback (most recent call last):
File "<pyshell#88>", line 3, in <module>
if sub_list[i] in my_list and sub_list[i+1] in my_list:
IndexError: list index out of range
我以为我做错了什么!你知道吗
代码的问题是
range
函数将i
的值从“0”返回到“len(sub\u list)-1”。但是在for
循环中,您试图访问sub_list
的“i+1”元素。因此,当“i”的值为len(sub_list) - 1
时,“i+1”变为“len(sub\u list)”,它不是子列表的有效索引(列表的有效索引总是在0到len(list)-1的范围内)。你知道吗因此,如果您更改range函数的endbound,您的代码将正常工作。i、 e.您需要使用:
相关问题 更多 >
编程相关推荐