Python 列表迭代为单行

dfe*_*nan 4 python list

我目前正在学习 Python。

我该如何放置:

dates = list()  
for entry in some_list:  
    entry_split = entry.split()    
    if len(entry_split) >= 3:  
        date = entry_split[1]
        if date not in dates:  
            dates.append(date)
Run Code Online (Sandbox Code Playgroud)

变成 Python 中的一行代码?

ken*_*ytm 6

而不是 1-liner,使用 3-liner 可能更容易理解。

table = (entry.split() for entry in some_list)
raw_dates = (row[1] for row in table if len(row) >= 3)
# Uniquify while keeping order. http://stackoverflow.com/a/17016257
dates = list(collections.OrderedDict.fromkeys(raw_dates))
Run Code Online (Sandbox Code Playgroud)

  • @dfernandes__:您需要先“导入集合”。并且您需要使用 Python 2.7 或 3.x。 (2认同)