[英]check several lists with several for loops
keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']
我想对List
中的每个元素和keylist
每个元素进行操作:
for n in List:
for key in keylist:
if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
try:
print(n) #placeholder
except:
pass
基本上,我想检查keylist
的第一个split元素是否是List
的元素,但是Output是一个错误:
TypeError: list indices must be integers or slices, not str
因为您在List [n]中使用的n不是List中元素的索引。
for n in List: # here n is not the index to element in list but element itself.
for key in keylist: # so you can't use List[n] below e.g. n is 'A' in first iteration
if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
try:
print(n) #placeholder
except:
pass
如果需要列表中元素的索引,请使用以下代码。
for idx, ele in enumerate(List):
for key in keylist:
if key.split('/')[0] == List[idx] and key.split('/')[-1] == 'P':
try:
print(List[idx]) # or print(ele)
except:
pass
在这里, ele == List[idx]
keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']
for n in List:
for key in keylist:
if ((key.split('/')[0] in List) and (key.split('/')[1] == 'P')):
try:
print(n) #placeholder
except:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.