我有一个字符串列表,每个字符串代表书籍和它们的一些属性,例如
# each book followed by the price and the name of the genre
book_names = ['love 3 romance',
'rose 6 drama',
'flower 7 nice_story']
我想以某种方式为这些书中的每一本创建一个新对象,并制作其字符串描述属性的其他部分。
这是我尝试过的(显然,它不起作用):
class Book_Class():
price=0
genre=''
book_content=[]
for i in book_names:
name=i.split()[0]
name=Book_Class()
name.price=i.split()[1]
name.genre=i.split()[2]
也许有一种简单的方法可以实现我所追求的目标(请告诉我,因为我对编程很新...)。
答案 0 :(得分:7)
有几种方法:
使用字典,在很多情况下绰绰有余:
keys = ['name', 'price', 'gender']
book = { k: v for k, v in zip(keys, i.split()) }
为您的Book
班级提供有意义的__init__
初始化程序:
class Book(object):
name = ''
price = 0
gender = None
def __init__(self, name, price, gender):
self.name = name
self.price = price
self.gender = gender
并将解析后的值传递给:
Book(*i.split())
作为最后的手段,您可以使用setattr
在现有对象上设置任意属性:
book = Book()
for attr, value in zip(keys, i.split()):
setattr(book, attr, value)
答案 1 :(得分:1)
执行相同任务的另一种方法是使用命名元组。
book_names = ['love 3 romance',
'rose 6 drama',
'flower 7 nice_story']
from collections import namedtuple
book = namedtuple("Book", "name price genre")
# convert book_names to books
[book(*b.split()) for b in book_names]
Output: [Book(name='love', price='3', genre='romance'),
Book(name='rose', price='6', genre='drama'),
Book(name='flower', price='7', genre='nice_story')]
然后您可以按预期访问属性
book1 = [book(*b.split()) for b in book_names][0]
print book1.name, book1.price, book1.genre
Output: ('love', '3', 'romance')
如果您想使用第一个参数作为变量名,您可以这样做:
book = namedtuple("Book", "price genre")
for b in book_names:
globals()[b.split()[0]] = book(*b.split()[-2:])
# now you can access your books:
love.price
答案 2 :(得分:0)
Ashwini Chaudhary给出的答案是使用globals()
# each book followed by the price and the name of the genre
book_names = ['love 3 romance',
'rose 6 drama',
'flower 7 nice_story']
class Book_Class():
price=0
genre=''
book_content=[]
for i in book_names:
nnn='name'
globals()[nnn]=i.split()[0]
name=Book_Class()
name.price=i.split()[1]
name.gender=i.split()[2]