user1825241
user1825241

Reputation: 896

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]

Upvotes: 0

Views: 607

Answers (2)

radious
radious

Reputation: 830

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?

Upvotes: 1

mariano
mariano

Reputation: 1367

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.

Upvotes: 0

Related Questions