首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python 3读取数组(列表?)转变成新的价值观

python 3读取数组(列表?)转变成新的价值观
EN

Stack Overflow用户
提问于 2013-11-03 16:34:32
回答 2查看 5.2K关注 0票数 0

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

代码语言:javascript
复制
items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]

我需要把它解读成新的值,以便将来的计算。例如:

代码语言:javascript
复制
item1 = this
size1 = 5
unit1 = cm

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-03 16:49:54

Python中的数组可以有两种类型-- Lists & Tuples

list是可变的(也就是说,您可以根据需要更改元素)

tuple是不可变的(只读数组)

list[1, 2, 3, 4]表示

tuple(1, 2, 3, 4)表示

因此,给定的数组是list of tuples

可以在列表中嵌套元组,但不能在元组中嵌套列表。

这是更多的丙酮-

代码语言:javascript
复制
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)

代码语言:javascript
复制
['this', 5, 'cm']
['that', 3, 'mm']
['other', 15, 'mm']
15
9
45

更新:后续this comment & this answer我更新了上面的代码。

票数 1
EN

Stack Overflow用户

发布于 2013-11-03 17:02:58

接下来是阿什什·尼廷·帕蒂尔的回答。

如果将来有三个以上的项目,您可以使用星号来解压元组中的项目。

代码语言:javascript
复制
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:看起来您需要使用第二个元组列表来定义每个值元组的属性名称:

代码语言:javascript
复制
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

这里的警告是,您需要确保支持列表中的元素与值列表中的元素顺序匹配。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19755206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档