简体   繁体   English

如何迭代到列表中的元组

[英]How to iterate into a list into a tuple

I am writing a program where I have a bunch of tuples in a list like this: 我正在编写一个程序,我在这样的列表中有一堆元组:

[('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2') etc. [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')等。

The tuples are the format 元组是格式

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

I do not know how to access the information about the month only. 我不知道如何访问有关该月的信息。

I have tried: 我努力了:

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

I am working in python 3. 我在python 3中工作。

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))

Output: 输出:

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

The basic idea is to get the second item of the tuple, which is a string, then get the first two characters of the string. 基本思路是获取元组的第二项,即字符串,然后获取字符串的前两个字符。 Those characters describe the month. 那些角色描述了这个月。

I'll go through the process step by step. 我会一步一步地完成这个过程。

Let's say you have a list called data : 假设您有一个名为data的列表:

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

Take the first item: 拿第一项:

item = data[0]

The value of item is the tuple ('a01', '01-24-2011', 's1') . item的值是元组('a01', '01-24-2011', 's1')

Take the second element of item : 采取的第二个元素item

date = item[1]

The value of date is the string '01-24-2011' . date的值是字符串'01-24-2011'

Take the first two characters of date : date的前两个字符:

month = date[:2]

The value of month is the string 01 . month的值是字符串01 You can convert this into an integer: 您可以将其转换为整数:

month = int(month)

Now the value of month is 1 . 现在month的值是1

Using list comprehensions: 使用列表推导:

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

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

print(months)
>>> 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']

you can use map and lambda 你可以使用map和lambda

如果您只想要一个独特的月份列表并且订单无关紧要使用一套:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM