我想在两个大小为4的列表上进行两个for循环。
list_01 = [0,1,2,3] and list_02 = [0,1,2,3]
我已经做了这样的声明:
for ii in range(len(list_01)):
for jj in range(len(list_02)):
# if list_01[ii] != list_02[jj]:
if list_01[0] != list_02[1]:
...
我想避免像这样反向执行“相同”操作:
# if list_01[ii] != list_02[jj]:
if list_01[1] != list_02[0]:
...
只需一次将每个值进行比较。
感谢您的帮助!
答案 0 :(得分:0)
如果您要比较list_01[ii] != list_02[jj]
这样的ii <= jj
,那么只需确保您从ii
开始而不是从内部循环的0
开始
for ii in range(len(list_01)):
# start at ii, not 0, to maintain invariant that ii <= jj
for jj in range(ii, len(list_02)):
if list_01[ii] != list_02[jj]:
# do stuff
编辑:正如评论所观察到的那样,这不是Python风格。最好避免使用索引,而直接直接获取所需的项目:
for ii, item_01 in enumerate(list_01):
for item_02 in list_02[ii:]: # slice from ii to end
if item_01 != item_02:
# do stuff
答案 1 :(得分:0)
如果您要省略相同的索引对,则应该这样做:
from itertools import product
list_01 = [0,1,2,3]
list_02 = [0,1,2,3]
i1 = range(len(list_01))
i2 = range(len(list_02))
indices = []
for p in product(i1, i2):
if sorted(p) not in indices:
indices.append(list(p))
for i, j in indices:
#do stuff