当前输出:
['Jay', 'Boon', 'Sue', 'Tim', 'Lia', 'John', 'Abe']
[]
[]
理想输出:
['Jay', 'Boon', 'Sue', 'Tim', 'Lia', 'John', 'Abe']
[20, 40, ,26, 28, 21, 91, 25]
[...]
NamesFromForum = ['Jay','Boon','Jay','Sue','Tim','Lia','Lia','John','John','Abe']
AgesFromForum = [20,40,30,26,28,21,18,91,10,25]
LocFromForum = ['BA','CA','NM','CO','AL','NY','TX','NV','MN','SO']
NameNoDup = []
ageAlignName = []
LocAlignName =[]
for x in NamesFromForum:
if x not in NameNoDup:
NameNoDup.append(x)
for y in AgesFromForum:
for x in NamesFromForum:
if x not in NameNoDup:
AgesFromForum.append(y)
for z in LocFromForum:
for x in NamesFromForum:
if x not in NameNoDup:
LocFromForum.append(z)
print(NameNoDup)
print(ageAlignName)
print(LocAlignName)```
最好使用控制集来确保您不会添加重复的名称,而不是每次都扫描列表(这样更快)。然后使用zip来对齐列表。像这样:
NamesFromForum = ['Jay','Boon','Jay','Sue','Tim','Lia','Lia','John','John','Abe']
AgesFromForum = [20,40,30,26,28,21,18,91,10,25]
LocFromForum = ['BA','CA','NM','CO','AL','NY','TX','NV','MN','SO']
NameNoDup = []
ageAlignName = []
LocAlignName =[]
nameSet = set()
for name, age, loc in zip(NamesFromForum, AgesFromForum, LocFromForum):
if name not in nameSet:
NameNoDup.append(name)
ageAlignName.append(age)
LocAlignName.append(loc)
nameSet.add(name)
print(NameNoDup)
print(ageAlignName)
print(LocAlignName)
输出:
['Jay', 'Boon', 'Sue', 'Tim', 'Lia', 'John', 'Abe']
[20, 40, 26, 28, 21, 91, 25]
['BA', 'CA', 'CO', 'AL', 'NY', 'NV', 'SO']