John Collins
John Collins

Reputation: 37

python 3 read array (list?) into new values

I have the following array, with (I think) sub lists within it:

items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]

I need to read it into new values for future calculations. For example:

item1 = this
size1 = 5
unit1 = cm

item2 = that
size2 = 3
unit2 = mm
...

There may be more than 3 items in future arrays, so ideally some form of loop is needed?

Upvotes: 0

Views: 6326

Answers (2)

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13373

Arrays in Python can be of 2 types - Lists & Tuples.
list is mutable (i.e. you can change the elements as & when you wish)
tuple is immutable (read only array)

list is represented by [1, 2, 3, 4]
tuple is represented by (1, 2, 3, 4)

Thus, the given array is a list of tuples!
You can nest tuples in lists but not lists in tuples.

This is more pythonic -

items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]

found_items = [list(item) for item in items]

for i in range(len(found_items)):
    print (found_items[i])

new_value = int(input ("Enter new value: "))

for i in range(len(found_items)):
    recalculated_item = new_value * found_items[i][1]
    print (recalculated_item)

Output from above code (taking input as 3)

['this', 5, 'cm']
['that', 3, 'mm']
['other', 15, 'mm']
15
9
45

Update : Following up on this comment & this answer I've updated the above code.

Upvotes: 1

JeremyFromEarth
JeremyFromEarth

Reputation: 14344

Following on Ashish Nitin Patil's answer...

If there are are going to be more than three items in the future you can use the asterisk to unpack the items in the tuples.

items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]
for x in items:
    print(*x)

#this 5 cm
#that 3 mm
#other 15 mm

Note: Python 2.7 doesn't seem to like the asterisk in the print method.

Update: It looks like you need to use a second list of tuples that defines the property names of each value tuple:

props = [('item1', 'size2', 'unit1'), ('item2', 'size2', 'unit2'), ('item3', 'size3', 'unit3')]
values = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]

for i in range(len(values)):
    value = values[i]
    prop = props[i]
    for j in range(len(item)):
        print(prop[j], '=', value[j])

# output
item1 = this
size2 = 5
unit1 = cm
item2 = that
size2 = 3
unit2 = mm
item3 = other
size3 = 15
unit3 = mm

The caveat here is that you need to make sure that the elements in the props list are matched sequentially with the elements in the values list.

Upvotes: 0

Related Questions