gpt4 book ai didi

python - 将作为另一个列表元素的列表元素从字符串转换为整数

转载 作者:行者123 更新时间:2023-12-01 09:23:23 25 4
gpt4 key购买 nike

有一个多行字符串:

mytesttring='''3
7 4
2 4 6
8 5 9 3'''

我可以将其转换为元素为字符串的列表列表。

testlist=[elements.split() for elements in mytesttring.strip().split("\n")]

print(testlist)

[['3']['7','4'],['2','4','6'],['8','5','9','3']]

我们如何将元素从字符串更改为整数。这样输出将是:

[[3][7,4],[2,4,6],[8,5,9,3]]

最佳答案

您可以通过 map 在列表理解中转换为 int:

testlist = [list(map(int, elements.split())) for elements in \
mytesttring.strip().split('\n')]

关于python - 将作为另一个列表元素的列表元素从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com