简体   繁体   中英

The best way to convert python list items from string to number

I have a list like this:

id=['"1',
 '"1',
 '"2',
 '"2',
 '"1',
 '"1',
 '"2',
 '"2'
]

what is the best way to convert all the item to numbers, now they are strings.Out put should like:

id=[1,
 1,
 2,
 2,
 ...
 2]

You can try:

numbers = [int(s.replace('"', '')) for s in id]
print(numbers)
# [1, 1, 2, 2, 1, 1, 2, 2]

and please don't use id as a variable name, as it's already a name used by python

You can also make a loop to convert every item into an integer

for i in range(len(id)):
     id[i] = int(id[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM