Home > database >  how to modify certain element in a list
how to modify certain element in a list

Time:10-22

i have a list about more than 3000 elements and it looks like this :

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=['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. Also the number after the kor is is random, so I don't think I can use a for loop to deal with it.

CodePudding user response:

What makes you think you can't use a for-loop?

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']]

CodePudding user response:

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 ]

  • Related