[英]Split integers in string - python
I've got a bunch of numbers in a string. 我有一串数字。 I want to split them into individual digits so I can do more with them later.
我想将它们分成单个数字,以便以后再使用它们。
number = [6, 18, 6, 4, 12, 18, 0, 18]
I want to split these like so.... ex: 6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8 我想像这样分割这些...例如:6、1、8、6、4、1、2、1、8、0、1、8
I've tried split(), I've tried list(str(number)), I've tried converting these to strings and integers and I have tried searching stackoverflow. 我试过split(),试过list(str(number)),试过将它们转换为字符串和整数,并试过搜索stackoverflow。
In other searches I keep seeing a list comprehension example like this, which I don't understand and don't get the desired result after trying: [int(i) for i in str(number)] 在其他搜索中,我不断看到这样的列表理解示例,尝试后,我不理解也无法获得期望的结果:[int(i)for str(number)中的i]
help?? 救命??
First you have to consider every element of the list as a string, and then cast back every character to an integer. 首先,您必须将列表中的每个元素都视为一个字符串,然后将每个字符都转换为整数。
def customSplit(l):
result = []
for element in l:
for char in str(element):
result.append(int(char))
return result
print(customSplit([6, 18, 6, 4, 12, 18, 0, 18]))
# prints [6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]
How about a list comprehension : 列表理解如何:
[ digit for x in number for digit in str(x) ]
which produces a list of strings: 产生一个字符串列表:
['6', '1', '8', '6', '4', '1', '2', '1', '8', '0', '1', '8'] ['6','1','8','6','4','1','2','1','8','0','1','8'
or 要么
[ int(digit) for x in number for digit in str(x) ]
if you'd prefer a list of single-digit integers: 如果您希望使用一位整数列表:
[6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]
You can use itertools.chain
like so: 您可以像这样使用
itertools.chain
:
>>> list(map(int, chain.from_iterable(map(str, numbers))))
[6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]
I posted this mainly so I could compare it to a Coconut equivalent: 我主要发布了此内容,因此可以将其与等效的椰子进行比较:
>>> numbers |> map$(str) |> chain.from_iterable |> map$(int) |> list
while looks nicer. 虽然看起来更好。 If you like Unicode characters, you can replace
|>
with ↦
: 如果你喜欢Unicode字符,你可以替换
|>
与↦
:
>>> numbers ↦ map$(str) ↦ chain.from_iterable ↦ map$(int) ↦ list
In standard Python, a list comprehension is probably more readable. 在标准Python中,列表理解可能更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.