[英]Converting all the elements of a list from string to integer in Python
[英]Modify all elements in a python list and change the type from string to integer
我有一個數字列表,看起來像['3,2,4', '21,211,43', '33,90,87']
我猜此時元素被視為字符串。
我想刪除倒置的逗號並制作一個包含所有這些數字的列表。
預期輸出為[3,2,4, 21,211,43, 33,90,87]
另外,我想知道元素的類型是否從字符串轉換為整數。
有人請幫助我!
以下情況如何:
result = []
# iterate the string array
for part in ['3,2,4', '21,211,43', '33,90,87']:
# split each part by , convert to int and extend the final result
result.extend([int(x) for x in part.split(",")])
print(result)
輸出:
$ python3 ~/tmp/so.py
[3, 2, 4, 21, 211, 43, 33, 90, 87]
>>> your_list = ['3,2,4', '21,211,43', '33,90,87']
>>> your_list = [int(num) for item in your_list for num in item.split(",")]
>>> print(your_list)
[3, 2, 4, 21, 211, 43, 33, 90, 87]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.