[英]Python Convert Int List to Decimal string then back to Int List
I need to pass a list of numbers in a 3D program I'm using but it can only pass a single value. 我需要在我正在使用的3D程序中传递数字列表,但它只能传递一个值。 I want to pass the list as a single string separated by decimal points and then later convert that string back to a list. 我想将列表作为由小数点分隔的单个字符串传递,然后再将该字符串转换回列表。 Here's the outcome I'm looking for: 这是我要寻找的结果:
a=[8,9,10,11] # will always contain integers a = [8,9,10,11]#将始终包含整数
list elements converted to decimal then join as a string 列出转换为十进制的元素,然后以字符串形式加入
a=".8.9.10.11" a =“。8.9.10.11”
then later on convert that string back to a list 然后稍后将该字符串转换回列表
a=[8,9,10,11] a = [8,9,10,11]
I'm thinking it's a combo of the map() and join() function but I'm not exactly sure. 我在想这是map()和join()函数的组合,但我不确定。 Thanks for any help! 谢谢你的帮助!
Starting with a
as [8,9,10,11]
: 以启动a
为[8,9,10,11]
First one would be (to string): 第一个是(字符串):
a = ''.join('.{0}'.format(d) for d in a)
# ".8.9.10.11"
Second would be (back to list of ints again): 第二个是(再次返回整数列表):
a = [int(i) for i in a.split('.')[1:]]
# [8, 9, 10, 11]
To convert that list to a string, just do: 要将列表转换为字符串,只需执行以下操作:
a=[8,9,10,11]
b = '.'+'.'.join(a)
>>> print b
.8.9.10.11
To get the list back from the string, you do: 要从字符串中获取列表,请执行以下操作:
b = '.8.9.10.11'
a = b[1:].split('.')
>>> print a
[8,9,10,11]
a = [8, 9, 10, 11] b = '.' + '.'.join(str(x) for x in a) v = [int(x) for x in b.split('.')[1:]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.