gpt4 book ai didi

python在列表循环中引用前面的项目

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:08 24 4
gpt4 key购买 nike

我正在尝试遍历列表,但同时引用之前的项目以便我进行比较。

这是我的代码:

list1=[(1,'a','hii'),(2,'a','byee'),(3,'a','yoo'),(4,'b','laa'),(5,'a','mehh')]

我想遍历我的 list1 元组,如果元组中的第二个值与之前元组中的第二个值相同(均为 =='a'),则连接元组中的第三项。

我想要的输出:

list2=[('a','hii,byee,yoo'),('b','laa'),('a','mehh')]

我尝试过的:

for item in list1:
for item2 in list2:
if item[0]==(item2[0]-1) and item[1]==item2[1]:
print item[2]+','+item2[2]
elif item[0] != item2[0]-1:
continue
elif item[0]==(item2[0]-1) and item[1] != item2[1]:
print item[2]

错误的输出

hii,byee
byee,yoo
yoo
laa

从前 2 个输出来看,循环似乎只查看前面的值,而不查看前面的 2 个或更多值。因此它只将 2 个单词连接在一起,而不是它应该有的 3 个。输出最终也有重复。

我该如何解决这个问题?

最佳答案

我使这种方式变得比需要的更难

def combine(inval):
outval = [inval[0]]
for item in inval[1:]:
if item[0] == outval[-1][0] + 1 and item[1] == outval[-1][1]:
outval[-1] = (item[0], item[1], ",".join([outval[-1][2], item[2]]))
continue
outval.append(item)
return [(item[1], item[2]) for item in outval]

然后测试它...

list1 = [(1,'a','hii'),(2,'a','byee'),(3,'a','yoo'),(4,'b','laa'),(5,'a','mehh')]
list2 = [(1,'a','hii'),(3,'a','byee'),(4,'a','yoo'),(5,'b','laa'),(6,'a','mehh')]
list3 = [(1,'a','hoo'),(3,'a','byee'),(5,'a','yoo'),(6,'a','laa'),(7,'a','mehh'),(9, 'b', 'nope')]

for l in (list1, list2, list3):
print "IN:", l
print "OUT:", combine(l)
print

输出

IN: [(1, 'a', 'hii'), (2, 'a', 'byee'), (3, 'a', 'yoo'), (4, 'b', 'laa'), (5, 'a', 'mehh')]
OUT: [('a', 'hii,byee,yoo'), ('b', 'laa'), ('a', 'mehh')]

IN: [(1, 'a', 'hii'), (3, 'a', 'byee'), (4, 'a', 'yoo'), (5, 'b', 'laa'), (6, 'a', 'mehh')]
OUT: [('a', 'hii'), ('a', 'byee,yoo'), ('b', 'laa'), ('a', 'mehh')]

IN: [(1, 'a', 'hoo'), (3, 'a', 'byee'), (5, 'a', 'yoo'), (6, 'a', 'laa'), (7, 'a', 'mehh'), (9, 'b', 'nope')]
OUT: [('a', 'hoo'), ('a', 'byee'), ('a', 'yoo,laa,mehh'), ('b', 'nope')]

这既保证第 0 个索引处的序号,也保证第 1 个索引处的值相等。

关于python在列表循环中引用前面的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37891848/

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