gpt4 book ai didi

python - 列表理解与实例

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:13 25 4
gpt4 key购买 nike

我正在尝试列表理解,但遇到以下问题。

class Programmer():
def __init__(self, name, years_at_umich=1, programs_written=0):
self.name = name
self.seniority = years_at_umich
self.bonus_points = random.randrange(1000)
self.programs_written = programs_written

def shout(self, phrase_to_shout):
print phrase_to_shout # print is for ppl!

def __str__(self):
return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

def year_at_umich(self):
return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups

打印输出

[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]

我正在尝试使用列表理解从上面的 prog_tups 列表中创建一个 Programmer 实例列表,并将该列表保存在变量 programmers 中。

我当前的代码如下,我没有得到回溯,但什么也没有发生:

programmers = [item for item in prog_tups]

最佳答案

如果您还没有自定义 Programmer 类,请考虑使用 collections.namedtuple子类:

import collections

Programmer = collections.namedtuple('Programmer', 'name seniority programs_written')
prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(n, s, p) for n,s,p in prog_tups]

# the first programmer
print programmers[0]

输出:

Programmer(name='Albert', seniority=1, programs_written=10)

要处理您现有的自定义类,请使用以下方法:

prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(*t) for t in prog_tups]

# the first programmer
print programmers[0]

输出:

My name is Albert, and I've been at UMich for about 1 years.

关于python - 列表理解与实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com