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 の配列には、Lists&の 2 つのタイプがありTuplesます。
list変更可能です (つまり、必要に応じて要素を & として変更できます)
tuple不変です (読み取り専用配列)

list によって表される によって[1, 2, 3, 4]
tuple表される(1, 2, 3, 4)

したがって、指定された配列listtuples!
リストでタプルをネストできますが、タプルでリストをネストすることはできません。

これはより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 に答える