2024-05-16 21:44:54 发布
网友
我当前的代码如下所示,我使用try和except从列表索引传递异常,有时“text”的长度可能小于3。我在找更漂亮的方法。请告诉我你的想法,谢谢。你知道吗
for item in items: text = item.splitlines() try: name = text[0] except: name = "" try: tag = text[1] except: tag = "" try: age = text[2] except: age = ""
itertools有izip_longest():
itertools
izip_longest()
keys = ['name', 'tag', 'age'] name, tag, age = (item[1] for item in izip_longest(keys, text, fillvalue=""))
可以说,当你想要一个dict的时候,这是非常有用的:
dict
dict(izip_longest(keys, text, fillvalue=""))
这里有一种方法:
text = item.splitlines() name, tag, age = (text + [""] * 3)[:3]
itertools
有izip_longest()
:可以说,当你想要一个
dict
的时候,这是非常有用的:这里有一种方法:
相关问题 更多 >
编程相关推荐