在python中迭代/检查子列表

2024-06-01 00:59:01 发布

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

我有一个包含子列表的列表,每个子列表包含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

我以为我做错了什么!你知道吗


Tags: andin元素列表forifmylist
1条回答
网友
1楼 · 发布于 2024-06-01 00:59:01

代码的问题是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.您需要使用:

for i in range (0,len(sub_list)-1):
#                               ^ subtracting one to make it fall in valid range

相关问题 更多 >