Skip to main content
 首页 » 编程设计

python之如何用python方式在一行中写这个

2025年05月04日12zhengyun_ustc

我是 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?] 

请您参考如下方法:

get = operator.itemgetter(4,5) 
w_topic = [get(line.split()) for line in lines]