[英]how to modify certain element in a list
i have a list about more than 3000 elements and it looks like this :我有一个关于 3000 多个元素的列表,它看起来像这样:
a=['>KOR1231','Seoul','HKU', '1992/3/21']
and I need to loop them all to a new list b and it should look like this:我需要将它们全部循环到一个新列表 b 中,它应该如下所示:
b=['KOR1231','Seoul','HKU', '1992/3/21']
So I need to get rid of the ">" in the list, and I can't just replace it with ```a[0]="KOR1231" since I have more than 3000 lines to go.所以我需要去掉列表中的“>”,我不能只用```a[0]="KOR1231" 替换它,因为我有3000多行要走。 Also the number after the kor is is random, so I don't think I can use a for loop to deal with it.
另外 kor 后面的数字是随机的,所以我不认为我可以使用 for 循环来处理它。
What makes you think you can't use a for-loop?是什么让您认为不能使用 for 循环?
flight_lst = [
['>KOR1231','Seoul','HKU', '1992/3/21'],
['>KOR9743','Paris','CDG', '1990/1/12']
]
for flight in flight_lst:
flight[0] = flight[0][1:]
print(flight_lst)
# [['KOR1231', 'Seoul', 'HKU', '1992/3/21'],
# ['KOR9743', 'Paris', 'CDG', '1990/1/12']]
Or alternatively, if you want to produce a new list without modifying the old list:或者,如果您想在不修改旧列表的情况下生成新列表:
old_lst = [
['>KOR1231','Seoul','HKU', '1992/3/21'],
['>KOR9743','Paris','CDG', '1990/1/12']
]
new_lst = [[flight[0][1:]] + flight[1:] for flight in old_lst]
print(new_lst)
# [['KOR1231', 'Seoul', 'HKU', '1992/3/21'],
# ['KOR9743', 'Paris', 'CDG', '1990/1/12']]
Or if you're comfortable with star-expansion:或者,如果您对明星扩张感到满意:
old_lst = [
['>KOR1231','Seoul','HKU', '1992/3/21'],
['>KOR9743','Paris','CDG', '1990/1/12']
]
new_lst = [[name[1:]] + remainder for name,*remainder in old_lst]
print(new_lst)
# [['KOR1231', 'Seoul', 'HKU', '1992/3/21'],
# ['KOR9743', 'Paris', 'CDG', '1990/1/12']]
Not sure if i understood your question correctly, but if you are only trying to locate and remove any ">" in the strings of the list you can try below.不确定我是否正确理解了您的问题,但如果您只是想在列表的字符串中找到并删除任何“>”,您可以尝试以下操作。
Example:例子:
b = [i.replace(">","") for i in a ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.