从元组列表中查找特定项

时间:2016-01-05 13:46:20

标签: python python-3.x

portfolio= [ 
( "Purchase Date:23-Aug-2015", "Purchase Price:43.50", "Shares:25",      'Symbol:CAT', "Current Price:92.45" ), 
( "Purchase Date:15-Mar-2013", "Purchase Price:42.80", "Shares:50",     'Symbol:DD', "Current Price:51.19" ), 
( "Purchase Date:7-Dec-2014", "Purchase Price:42.10", "Shares:75", 'Symbol:EK', "Current Price:34.87" ), 
( "Purchase Date:6-Dec-2013", "Purchase Price:37.58", "Shares:100", 'Symbol:GM', "Current Price:37.58" ) 
] 

# loop to iterate over each item in list and print each item out
for a in portfolio:
    print (a[0:5])

这是我的代码,我想打印一个元组中的特定项目,我该怎么做?

我想从Purchase price打印出7-Dec-2014

3 个答案:

答案 0 :(得分:4)

您可能最好将数据放入词典,以便更清晰地查看。

portfolio = [
{"Purchase Date":"23-Aug-2015", "Purchase Price":43.50, "Shares":25, "Symbol":"CAT", "Current Price":92.45},
{"Purchase Date":"15-Mar-2013", "Purchase Price":42.80, "Shares":50, "Symbol":"DD", "Current Price":51.19},
{"Purchase Date":"7-Dec-2014", "Purchase Price":42.10, "Shares":75, "Symbol":"EK", "Current Price":34.87},
{"Purchase Date":"6-Dec-2013", "Purchase Price":37.58, "Shares":100, "Symbol":"GM", "Current Price":37.58}
]

for data in portfolio:
    if data["Purchase Date"] == "7-Dec-2014":
        print(data["Purchase Price"])

答案 1 :(得分:3)

您需要检查元组中的第一项是"Purchase Date:7-Dec-2014"。如果是,您可以在元组中打印第二个项目。以下是如何做到这一点:

portfolio= [
( "Purchase Date:23-Aug-2015", "Purchase Price:43.50", "Shares:25",      'Symbol:CAT', "Current Price:92.45" ),
( "Purchase Date:15-Mar-2013", "Purchase Price:42.80", "Shares:50",     'Symbol:DD', "Current Price:51.19" ),
( "Purchase Date:7-Dec-2014", "Purchase Price:42.10", "Shares:75", 'Symbol:EK', "Current Price:34.87" ),
( "Purchase Date:6-Dec-2013", "Purchase Price:37.58", "Shares:100", 'Symbol:GM', "Current Price:37.58" )
]

for transaction in portfolio:
    if transaction[0] == "Purchase Date:7-Dec-2014":
        print(transaction[1])

这段代码非常笨重,既不是Pythonic也不是漂亮的。表示这些数据的更自然的方式是使用字典,或者更具体地说,使用字典字典。我将使用交易日期作为与该日期对应的交易数据的关键。

transactions = {
  '23-Aug-2015' : { 'Purchase Price' : 43.50, 'Shares' : 25, 'Symbol' : 'CAT', 'Current Price': 92.45 },
  '15-Mar-2013' : { 'Purchase Price' : 42.80, 'Shares' : 50, 'Symbol' : 'DD', 'Current Price': 51.19 },
  '7-Dec-2014' : { 'Purchase Price' : 42.10, 'Shares' : 75, 'Symbol' : 'EK', 'Current Price': 34.87 },
  '6-Dec-2013' : { 'Purchase Price' : 37.58, 'Shares' : 100, 'Symbol' : 'GM', 'Current Price': 37.58 }
}

以下是使用字典实现相同目标的方法:

# For every key and value pair in transactions
for k, v in transactions.iteritems():
  # If we find a key with December 7th, 2014 as the date
  if k == '7-Dec-2014':
    # Print the purchase price of the transaction from that date.
    print v['Purchase Price']

这使您无需对字符串进行任何特殊解析即可访问数据。

答案 2 :(得分:2)

您可以遍历portfolio并检查您要查找的购买日期是否在任何元组中。如果是这样,只要购买价格在所有元组中始终处于相同位置,您就可以打印它。

for i in portfolio:
    if "Purchase Date:7-Dec-2014" in i:
        print (i[1])