![](/img/trans.png)
[英]How to extract a list of integer numbers from a list with strings and integers?
[英]Python list: Extract integers from list of strings
我有一個包含以下值的列表,它們實際上是列表中的字符串:
mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
如何提取每個值並使用上面列表中的每個值創建一個新列表?
我需要這樣的結果:
mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]
先感謝您
只需像這樣使用列表理解:
mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
output = [int(c) for c in ",".join(mylist).split(",")]
print(output)
Output:
[4, 1, 2, 1, 2, 120, 13, 223, 10]
這會生成單個值字符串,並將所有值分隔為單獨的字符串。 然后它可以使用int()
將它們轉換為整數並將其添加到新list
。
我會提供一個冗長但可能更容易理解的解決方案
mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10', '1', '']
separtedList = []
for element in mylist:
separtedList+=element.split(',')
integerList = []
for element in separtedList:
try:
integerList.append(int(element))
except ValueError:
pass # our string seems not not be an integer, do nothing
mylist = integerList
print(mylist)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.