[英]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.