简体   繁体   English

Python 将字符串拆分为包含整数、字符串和小数的列表

[英]Python split string into list with ints, strings and decimals

Im trying to split我试图分裂

dimensions = "M 0 0 C 65 1 130 1 194.6875 0 C 195 17 195 33 194.6875 50 C 130 49 65 49 0 50 C 0 33 0 17 0 0 z"

into list form where if I wanted to get 194.6875 I could do进入列表形式,如果我想得到194.6875我可以做

print(dimensions[8])

Im having trouble converting it to a list since there are multiple types.由于有多种类型,我无法将其转换为列表。

dimensions = "M 0 0 C 65 1 130 1 194.6875 0 C 195 17 195 33 194.6875 50 C 130 49 65 49 0 50 C 0 33 0 17 0 0 z"
dimensions = dimensions.split(" ")
print(float(dimensions[8]))

You can use the.split() method on a string and pass in the character you want to split on, ie:您可以在字符串上使用 .split() 方法并传入要拆分的字符,即:

dimensions = "M 0 0 C 65 1 130 1 194.6875 0 C 195 17 195 33 194.6875 50 C 130 49 65 49 0 50 C 0 33 0 17 0 0 z"
listDimensions = dimensions.split(' ')
x = float(listDimensions[8])
print(x)

After that it is a case of changing the data type of the item you want with something like str() , int() or float()之后,可以使用str()int()float()之类的方式更改所需项目的数据类型

You could split on space and convert to float the values that are not alphabetic strings您可以拆分空间并转换为浮动不是字母字符串的值

dimensions = "M 0 0 C 65 1 130 1 194.6875 0 C 195 17 195 33 194.6875 50 C 130 49 65 49 0 50 C 0 33 0 17 0 0 z"
values = [val if val.isalpha() else float(val) for val in dimensions.split(" ")]

print(values) # ['M', 0.0, 0.0, 'C', 65.0, 1.0, 130.0, 1.0, 194.6875, 0.0, 'C', 195.0, 17.0, 195.0, 33.0, 194.6875, 50.0, 'C', 130.0, 49.0, 65.0, 49.0, 0.0, 50.0, 'C', 0.0, 33.0, 0.0, 17.0, 0.0, 0.0, 'z']
print(values[8], type(values[8])) # 194.6875 <class 'float'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM