gpt4 book ai didi

python - 检查二维列表中的重复字符串

转载 作者:行者123 更新时间:2023-12-01 05:33:26 30 4
gpt4 key购买 nike

我有一个程序,其中有名称和类别的列表。我有按字母顺序排列的列表。现在我试图检查名称是否重复,将类添加到一个名称中。

我正在尝试编写一些代码,例如

如果名称已在列表中,则遍历名称,将类添加到该名称中。所以一个例子是,而不是

['Anita','phys 1443'], ['Anita','IE 3312']

我只想

['Anita','PHYS 1443','IE 3312']

我将如何以一种逻辑的方式做到这一点,而不使用任何类型的内置函数?我尝试比较诸如

之类的指数
if list[i][0] == list[i+1][0]

list[i+1][1] 附加到空列表。虽然这几乎奏效了,但在过程中的某些时候它会搞砸。这是我的尝试

size = len(c)
i = 0
c = [['Anita', 'PHYS 1443'], ['Anita', 'IE 3312'], ['Beihuang', 'PHYS 1443'], ['Chiao-Lin', 'MATH 1426'], ['Chiao-Lin', 'IE 3312'], ['Christopher', 'CSE 1310'], ['Dylan', 'CSE 1320'], ['Edmund', 'PHYS 1443'], ['Ian', 'IE 3301'], ['Ian', 'CSE 1320'], ['Ian', 'PHYS 1443'], ['Isis', 'PHYS 1443'], ['Jonathan', 'MATH 2325'], ['Krishna', 'MATH 2325'], ['Michael', 'IE 3301'], ['Nang', 'MATH 2325'], ['Ram', 'CSE 1320'], ['Taesu', 'CSE 1320'], ["Tre'Shaun", 'IE 3312'], ["Tre'Shaun", 'MATH 2325'], ["Tre'Shaun", 'CSE 1310']]
## Check if any names repeat
d.append(c[0][0])
while i < size - 1 :
if c[i][0] == c[i+1][0] :

d.append(c[i][1])
d.append(c[i+1][1])
else :
d.append(c[i+1][0])
d.append(c[i+1][1])
i = i + 1
print d

输出是。

['Anita', 'PHYS 1443', 'IE 3312', 'Beihuang', 'PHYS 1443', 'Chiao-Lin', 'MATH 1426', 'MATH 1426', 'IE 3312', 'Christopher', 'CSE 1310', 'Dylan', 'CSE 1320', 'Edmund', 'PHYS 1443', 'Ian', 'IE 3301', 'IE 3301', 'CSE 1320', 'CSE 1320', 'PHYS 1443', 'Isis', 'PHYS 1443', 'Jonathan', 'MATH 2325', 'Krishna', 'MATH 2325', 'Michael', 'IE 3301', 'Nang', 'MATH 2325', 'Ram', 'CSE 1320', 'Taesu', 'CSE 1320', "Tre'Shaun", 'IE 3312', 'IE 3312', 'MATH 2325', 'MATH 2325', 'CSE 1310']

最佳答案

你可能想要这样的东西:

d = []
vi = 0
c = [['Anita', 'PHYS 1443'], ['Anita', 'IE 3312'], ['Beihuang', 'PHYS 1443'], ['Chiao-Lin', 'MATH 1426'], ['Chiao-Lin', 'IE 3312'], ['Christopher', 'CSE 1310'], ['Dylan', 'CSE 1320'], ['Edmund', 'PHYS 1443'], ['Ian', 'IE 3301'], ['Ian', 'CSE 1320'], ['Ian', 'PHYS 1443'], ['Isis', 'PHYS 1443'], ['Jonathan', 'MATH 2325'], ['Krishna', 'MATH 2325'], ['Michael', 'IE 3301'], ['Nang', 'MATH 2325'], ['Ram', 'CSE 1320'], ['Taesu', 'CSE 1320'], ["Tre'Shaun", 'IE 3312'], ["Tre'Shaun", 'MATH 2325'], ["Tre'Shaun", 'CSE 1310']]
size = len(c)
## Check if any names repeat
while i < size - 1:
if c[i][0] == c[i+1][0] :
temp = c[i]
temp.append(c[i+1][1])
d.append(temp)
else :
d.append(c[i+1])
i = i + 1
print d

输出

>>> [['Anita', 'PHYS 1443', 'IE 3312'], ['Beihuang', 'PHYS 1443'],...,
["Tre'Shaun", 'MATH 2325', 'CSE 1310']]

关于python - 检查二维列表中的重复字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662972/

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