【问题标题】:python 3 read array (list?) into new valuespython 3将数组(列表?)读入新值
【发布时间】:2013-11-03 16:34:32
【问题描述】:

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

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

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

item1 = this
size1 = 5
unit1 = cm

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

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

【问题讨论】:

标签: arrays list python-3.x


【解决方案1】:

Python 中的数组可以有 2 种类型 - ListsTuples
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

更新:跟进this commentthis answer我已经更新了上面的代码。

【讨论】:

  • 也许我需要一种以不同方式写入原始数据的方法?我可以理解您是如何打印的,但最终我需要将大小分配给新的整数值并对其进行计算。所以,稍后我可以有大小 x 2 并得到 10(例如,其他值是 6 和 30)
  • 您可以随意使用item, size, unit 变量。我使用print 来展示如何在循环中使用它们。
【解决方案2】:

按照 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 列表中的元素按顺序匹配。

【讨论】:

  • 预期输出是: 1.program 从文本文件中读取项目数组。 2. 提示用户输入新值 3. 重新计算数组项的大小 我想我需要索引数组项,然后分配给新值以执行计算?
  • 我现在最后需要这样的东西:newvalue = int(input ("Enter new value:")) newsize2 = size2 * newvalue print (newsize2)
  • 我已经相应地更新了我的答案。请检查。
  • 是的,这可以打印数据,但我需要按照我上面的评论对其进行计算。我需要将数组部分写入新变量(我认为?)
猜你喜欢
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 2018-09-29
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多