我有以下数组,其中包含(我认为)子列表:
items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]我需要把它解读成新的值,以便将来的计算。例如:
item1 = this
size1 = 5
unit1 = cm
item2 = that
size2 = 3
unit2 = mm
...未来的数组中可能有3个以上的项,所以理想情况下需要某种形式的循环?
发布于 2013-11-03 16:49:54
Python中的数组可以有两种类型-- Lists & Tuples。
list是可变的(也就是说,您可以根据需要更改元素)
tuple是不可变的(只读数组)
list由[1, 2, 3, 4]表示
tuple由(1, 2, 3, 4)表示
因此,给定的数组是list of tuples!
可以在列表中嵌套元组,但不能在元组中嵌套列表。
这是更多的丙酮-
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更新:后续this comment & this answer我更新了上面的代码。
发布于 2013-11-03 17:02:58
接下来是阿什什·尼廷·帕蒂尔的回答。
如果将来有三个以上的项目,您可以使用星号来解压元组中的项目。
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注意:Python2.7似乎不喜欢print方法中的星号。
Update:看起来您需要使用第二个元组列表来定义每个值元组的属性名称:
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这里的警告是,您需要确保支持列表中的元素与值列表中的元素顺序匹配。
https://stackoverflow.com/questions/19755206
复制相似问题