我想在这些元组中创建标签

时间:2018-04-30 10:58:03

标签: python

你好我想在这些元组中创建一个列表,以便它打印代码旁边的标签示例“购买日期= 16年8月23日,购买价格= 43.50等等但我不断得到”ValueError:需要更多1解压缩值“

portfolio = ( "23-Aug-2016", 43.50, 25, 'CAT', 92.45 ),
( "15-Mar-2014", 42.80, 50, 'DD', 51.19 ),
( "7-Dec-2015", 42.10, 75, 'EK', 34.87 ),
( "6-Dec-2014", 37.58, 100, 'GM', 37.58 )

purchase , okay, shares, symbol, current = portfolio

print("Purchase date =", purchase)
print("Purchase price =", okay)
print("Shares =", shares)
print("symbol =", symbol)
print("Current price =", current)

i = 0
while i < len(portfolio):
print(portfolio[i])
i += 1

2 个答案:

答案 0 :(得分:0)

portfolio是一个只包含一个元组的元组。

>>> portfolio = ( "23-Aug-2016", 43.50, 25, 'CAT', 92.45 ),
>>> ( "15-Mar-2014", 42.80, 50, 'DD', 51.19 ),
(('15-Mar-2014', 42.8, 50, 'DD', 51.19),)
>>> ( "7-Dec-2015", 42.10, 75, 'EK', 34.87 ),
(('7-Dec-2015', 42.1, 75, 'EK', 34.87),)
>>> ( "6-Dec-2014", 37.58, 100, 'GM', 37.58 )
('6-Dec-2014', 37.58, 100, 'GM', 37.58)

>>> portfolio
(('23-Aug-2016', 43.5, 25, 'CAT', 92.45),)

如您所见,只包含第一个元组,因为赋值语句在该行结束。因为它以逗号结束,python创建了一个包含您定义的外部元组的外部元组。例如:

>>> x = 1
>>> x
1
>>> x = 1,
>>> x
(1,)
>>> 2,
(2,)

这会以类似于您的代码的方式将元组(1,)分配给x。代码中的以下每一行都会创建一个元组,但它不会绑定到任何变量,因此它会丢失,就像上面的2,一样。

您可以通过索引来解压缩内部元组:

>>> purchase, okay, shares, symbol, current = portfolio[0]
>>> purchase
'23-Aug-2016'
>>> okay
43.5
...
>>> current
92.45

你可能期待元组的元组(或列表)。您可以通过将整个表达式包装在()(或[]列表中)来实现:

portfolios = (("23-Aug-2016", 43.50, 25, 'CAT', 92.45 ),
                ( "15-Mar-2014", 42.80, 50, 'DD', 51.19 ),
                ( "7-Dec-2015", 42.10, 75, 'EK', 34.87 ),
                ('6-Dec-2014', 37.58, 100, 'GM', 37.58))

现在你可以迭代了元组:

for portfolio in portfolios:
    purchase, okay, shares, symbol, current = portfolio
    print(purchase, okay, shares, symbol, current)

<强>输出

23-Aug-2016 43.5 25 CAT 92.45
15-Mar-2014 42.8 50 DD 51.19
7-Dec-2015 42.1 75 EK 34.87
6-Dec-2014 37.58 100 GM 37.58

答案 1 :(得分:0)

我想你想这样做:

portfolio = [( "23-Aug-2016", 43.50, 25, 'CAT', 92.45 ),
    ( "15-Mar-2014", 42.80, 50, 'DD', 51.19 ),
    ( "7-Dec-2015", 42.10, 75, 'EK', 34.87 ),
    ( "6-Dec-2014", 37.58, 100, 'GM', 37.58 )]

for item in portfolio:
    purchase , okay, shares, symbol, current = item
    print("Purchase date =", purchase)
    print("Purchase price =", okay)
    print("Shares =", shares)
    print("symbol =", symbol)
    print("Current price =", current)

有些注意事项:

  • portfolio应为list
  • 使用Python中的for thing in iterable
  • 完成迭代