[英]How can I create an array in python using a for loop?
I have an array set out like this: 我有这样一个数组:
['age', 'height', 'weight']
and I need to "fill" the array with values from a list which contains objects with the values age, height and weight. 我需要用列表中的值“填充”数组,列表中包含年龄,身高和体重的对象。
For example: 例如:
for value in list:
age = value.age
height = value.height
weight = value.weight
"[{}, {}m, {}lb]".format(age, height, weight)
and I would like to get the desired output: 我想获得所需的输出:
[21, 1.77m, 160lb]
[25, 1.56m, 145lb]
etc for each object in the list. 等等,用于列表中的每个对象。
So the final output would end up being like this: 因此最终的输出结果将是这样的:
['age', 'height', 'weight']
[21, 1.77m, 160lb]
[25, 1.56m, 145lb]
If I understand then you are looking for: 如果我理解,那么您正在寻找:
head = [['age', 'height', 'weight']]
for obj in obj_list: # overriding built-in list is a bad idea
head += [obj.age, obj.height, obj.weight]
What will give you one array filled up with rest of the data: 什么将使您充满了其余数据的一个数组:
[['age', 'height', 'weight'],
[21, 1.77m, 160lb],
[25, 1.56m, 145lb]]
Is this what you are looking for? 这是你想要的?
You can format the string like this: 您可以像这样格式化字符串:
In [5]: a, h, w = 10, 1.70, 200
In [7]: print "[%d, %.2fm, %dlb]" % (a, h, w)
------> print("[%d, %.2fm, %dlb]" % (a, h, w))
[10, 1.70m, 200lb]
Note that combining these values with string suffixes converts the elements to strings, which may or may not be good. 请注意,将这些值与字符串后缀组合会将元素转换为字符串,这可能是好事,也可能不是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.