[英]Split each string in list and store in multiple arrays
I have a list that looks like this: ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
我有一个看起来像这样的列表: ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
I want to end up with these three arrays: [1,2,3,4]
and [0,0.5,1,1.5]
and [0,0.25,0.5,0.75]
我想结束于这三个数组: [1,2,3,4]
和[0,0.5,1,1.5]
和[0,0.25,0.5,0.75]
ie I want the first value of each list item and store it in an array, and do the same with the second and third values. 即我想要每个列表项的第一个值并将其存储在数组中,并对第二个和第三个值执行相同的操作。
I tried this 我试过了
for i in coordinates[:]:
number,x,y=i.split(' ')
also tried using number[]
and number.append
but none of these seem to work 也尝试使用number[]
和number.append
但是这些似乎都不起作用
This can be done as follows: 可以按照以下步骤进行:
list(zip(*(list(map(float, s.split())) for s in coordinates)))
First we loop through all strings in the list and split them 首先,我们遍历列表中的所有字符串并将其拆分
[s.split() for s in coordinates]
Then we map
the float
function over all the individual strings to convert them to floats: 然后,我们将float
函数map
到所有单个字符串上,以将它们转换为float:
[list(map(float, s.split())) for s in coordinates]
Then we use zip
to get them the way you want them. 然后,我们使用zip
以所需的方式获取它们。
Similar to @ikkuh's but with "configurable" types: 与@ikkuh类似,但具有“可配置”类型:
data = ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
tp = [int, float, float]
parsed = ((t(j) for t, j in zip(tp, record.split())) for record in data)
idx, x, y = (list(i) for i in zip(*parsed))
idx
# [1, 2, 3, 4]
x
# [0.0, 0.5, 1.0, 1.5]
y
# [0.0, 0.25, 0.5, 0.75]
Here is one approach without for loop , using lambda : 这是一种不带for循环的方法,使用lambda:
a=['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
print(list(zip(*list((map(lambda y:y.split(),a))))))
output: 输出:
[('1', '2', '3', '4'), ('0', '0.5', '1', '1.5'), ('0', '0.25', '0.5', '0.75')]
Creating three new list, and going through a input: 创建三个新列表,并进行输入:
input = ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
x_list = []
y_list = []
z_list = []
for i in input:
x, y, z = i.split(' ')
x_list.append(x)
y_list.append(y)
z_list.append(z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.