gpt4 book ai didi

python - 遍历 python 中的两个列表列表

转载 作者:行者123 更新时间:2023-11-28 22:41:31 25 4
gpt4 key购买 nike

我是 python 编程的新手,很难遍历两个列表列表。我的两个列表的格式如下:

L = [['cat', '1', '5'], ['cat', '7', '15'],['cat', '17', '20']]
A = [['coordOne', '1', '3'],['coordTwo', '8', '9'],['coordThree', '11', '13'],['coordFour', '18', '21']]

每个列表中的两个数字是开始和结束坐标,我想在比较两个列表时查看开始和结束坐标之间是否有重叠,然后将信息保存到新列表中。程序运行后我想要的列表将输出:

newList:[['cat', 'coordOne'],['cat', 'coordTwo', 'coordThree'], ['cat', 'coordFour']]

到目前为止我的代码是

    newList = []

for i in range(len(L)):
for j in range (len(A)):
if i[1] >= j[1] and i[1] <= j[2] or i[2] >= j[1] and i[2] <= j[2] or i[1] <= j[1] and i[2] >= j[2] and j[2] >= i[2] or i[1] <= j[1] and i[2] >= j[2]:
newList.append(L[i][0], A[j][0])


print (newList)

我收到“int”对象不可调用的错误。

最佳答案

您可以使用“zip”功能。

L = [['cat', '1', '5'], ['cat', '7', '15'],['cat', '17', '20']]
A = [['coordOne', '1', '3'],['coordTwo', '8', '9'],['coordThree', '11', '13'],['coordFour', '18', '21']]
newList = []

for (i,j) in zip(L, A):
if i[1] >= j[1] and i[1] <= j[2] or i[2] >= j[1] and i[2] <= j[2] or i[1] <= j[1] and i[2] >= j[2] and j[2] >= i[2] or i[1] <= j[1] and i[2] >= j[2]:
newList.append( (i[0], j[0]) )

关于python - 遍历 python 中的两个列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com