简体   繁体   English

如何使用for循环在python中创建数组?

[英]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.

相关问题 在 Python 中,如何使用 input + 'filename' 创建一个 while 循环 - In Python, How can I create a while loop using input + 'filename' 如何在 Python 中使用 for 循环创建嵌套字典? - How can I create a nested dictionary using a for loop in Python? 如何在 python 中使用循环创建多个线程 - How can I create multiple threads using a loop in python 如何使用for循环在python中编写2D数组 - How can I write a 2D array in python using for loop 如何在Python中创建循环并与之交互? - How can I create a loop, and interact with it, in Python? 如何使用 xpath 创建循环? - how can i create loop using xpath? 如何使用 Python 中的循环从单独的变量创建数组? - how to create an array from separate variables using a loop in Python? 如何在不使用 python 循环的情况下创建引用数据框和字典的当前列的条件列? - How can i create conditional column referring present columns of a dataframe and dictionary without using loop in python? 如何创建用于遍历数组元素的外部循环? - How can I create an external loop for going through elements of the array? 如何使用 Python 中的列表、数组或循环将 append 行值添加到 Google 工作表? - How can I append row values to a Google sheet using a list, array or loop in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM