我是python的新手,想知道我是否可以将以下for循环转换为pythonic方式的一行代码:
w_topic = []
for line in lines: #lines is a list of strings
word,topic = itemgetter(4,5)(line.split())
w_topic.append((word,topic))
我查看了列表推导但不确定如何在此处应用它?有可能在一条线上吗?我怎么知道某些东西是否可行是pythonic方式中的一行?
[(w,t) for w,t in how to fill here?]
答案 0 :(得分:5)
get = operator.itemgetter(4,5)
w_topic = [get(line.split()) for line in lines]
答案 1 :(得分:2)
这是你的一行
w_topic.extend([tuple(line.split()[4:6]) for line in lines])
我将以下内容视为完整代码:
lines = ['0 1 2 3 word1 topic1','0 1 2 3 word2 topic2','0 1 2 3 word3 topic3']
w_topic = []
w_topic.extend([tuple(line.split()[4:6]) for line in lines])
print w_topic
结果:
[(' word1',' topic1'),(' word2',' topic2'),(' word3& #39;,' topic3')]