2014-11-22 77 views
2

我寫一個程序,我有這樣一個名單一堆的元組:如何迭代到列表到一個元組

[('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')

元組的格式爲

(animal ID, date(month, day, year), station#) 

我不知道如何訪問有關月份的信息。

我曾嘗試:

months = []  
for item in list: 
    for month in item: 
     if month[0] not in months: 
      months.append(month[0]) 

我在Python工作3

回答

9
L = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')] 
for animal, date, station in L: 
    month, day, year = date.split('-') 
    print("animal ID {} in month {} at station {}".format(animal, month, station)) 

輸出:

animal ID a01 in month 01 at station s1 
animal ID a03 in month 01 at station s2 
1

的基本思想是讓元組,這是一個字符串的第二個項目,然後拿到前兩個字符的字符串。那些角色描述了這個月。

我會逐步完成這個過程。

比方說,你有一個名爲data列表:

data = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')] 

採取的第一項:

item = data[0] 

item值是元組('a01', '01-24-2011', 's1')

item第二元件:

date = item[1] 

date的值是字符串'01-24-2011'

date前兩個字符:

month = date[:2] 

month的值是字符串01。你可以轉換到這個整數:

month = int(month) 

現在的month1

1

使用列表理解:

data = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')] 

months = [item[1].split('-')[0] for item in data] 

print(months) 
0
>>> my_list = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')] 
>>> [ x for x in map(lambda x:x[1].split('-')[0],my_list) ] 
['01', '01'] 

您可以使用地圖和lambda

+0

downvote的任何原因? – Hackaholic 2014-11-23 01:49:58

+0

我發現gg.kaspersky提出的列表理解比map/lambda更好:[item [1] .split(' - ')[0] for my_list] – 2014-11-27 11:16:06

0

如果你只是想幾個月的唯一列表和順序無關緊要:

months = list({date.split("-",1)[0] for _, date, _ in l})