对列表中数据还原处理

bef=[]

aft=[]

org=[]

bef+=(input().split(‘,’))

org=bef[:]

for i in bef:

if(bef.count(i)<=1):

aft+=(i)

if(bef.count(i)>=2):

f=bef.count(i)

while(f>=2):

bef.remove(i)

f-=1

aft=bef

print(bef)

for i in bef:

if(i.isdigit()==True):

aft.append(int(i))

print(‘before:’,org)

print(‘after:’,aft,end=””)

#测试数据

1,7,6,7,7,True,’a’,9.8,’a’,True

#before: [1, 7, 6, 7, 7, True, ‘a’, 9.8, ‘a’, True]

#after: [1, 6, 7, 9.8, ‘a’, True]

#目标答案:

#目的

#不留重复数据,每个只留一个,原列表不变。

#目前问题

#i.isdigit()使用时遍历浮点数和字符串时会错误,又必须把input读入的str转换回去。

Jason990420
最佳答案

In Python, the iteration variable in a ‘for’ loop is essentially a placeholder that references the current item in the sequence being iterated over. It’s not meant to be directly modified within the loop. Attempting to modify it won’t have the intended effect and can lead to unexpected behavior.

for i in bef:
...
            bef.remove(i)
...

demo code

string = """1,7,6,7,7,True,'a',9.8,'a',True"""
old = string.split(",")
new = []
for item in old:
    if item not in new:
        new.append(item)
old = list(map(eval, old))
new = list(map(eval, new))
print(old)
print(new)
[1, 7, 6, 7, 7, True, 'a', 9.8, 'a', True]
[1, 7, 6, True, 'a', 9.8]
3周前 评论
讨论数量: 1
Jason990420

In Python, the iteration variable in a ‘for’ loop is essentially a placeholder that references the current item in the sequence being iterated over. It’s not meant to be directly modified within the loop. Attempting to modify it won’t have the intended effect and can lead to unexpected behavior.

for i in bef:
...
            bef.remove(i)
...

demo code

string = """1,7,6,7,7,True,'a',9.8,'a',True"""
old = string.split(",")
new = []
for item in old:
    if item not in new:
        new.append(item)
old = list(map(eval, old))
new = list(map(eval, new))
print(old)
print(new)
[1, 7, 6, 7, 7, True, 'a', 9.8, 'a', True]
[1, 7, 6, True, 'a', 9.8]
3周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!