0

我有以下数组,其中包含(我认为)子列表:

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

我需要将其读入新值以供将来计算。例如:

item1 = this
size1 = 5
unit1 = cm

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

未来数组中可能有超过 3 个项目,所以理想情况下需要某种形式的循环?

4

2 回答 2

1

Python 中的数组可以有 2 种类型 - Lists& Tuples
list是可变的(即您可以根据需要将元素更改为 &)
tuple是不可变的(只读数组)

list 表示[1, 2, 3, 4]
tuple为 表示为(1, 2, 3, 4)

因此,给定的数组是list一个tuples
您可以将元组嵌套在列表中,但不能将列表嵌套在元组中。

这更像是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)

上述代码的输出(以输入为 3)

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

更新:跟进此评论此答案,我已更新上述代码。

于 2013-11-03T16:49:54.007 回答
0

跟随 Ashish Nitin Patil 的回答......

如果将来要超过三个项目,您可以使用星号来解包元组中的项目。

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

注意:Python 2.7 似乎不喜欢 print 方法中的星号。

更新: 看起来您需要使用第二个元组列表来定义每个值元组的属性名称:

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

这里需要注意的是,您需要确保 props 列表中的元素与 values 列表中的元素按顺序匹配。

于 2013-11-03T17:02:58.937 回答