Python 列表迭代到一行

标签 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)

进入 Python 的单行代码?

最佳答案

用 3 行代码代替 1 行代码可能更容易理解。

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))

关于Python 列表迭代到一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201095/

相关文章:

python - 在python中构造一个从大到小的整数列表

Python:从方程结果创建嵌套列表

python 3.6.9锁屏

python - 方法参数中的命名空间

python - 使用 configparser 解析 ini 文件会给出 configparser.MissingSectionHeaderError ,第一行为 'ÿþ\n'

python - 小写django查询

Python:将字符串转换为函数名; getattr 还是等于?

python - 为什么 [[]]*10 是在 python 中创建 10 个空列表的列表而不是 [[]*10] 的方法?

r - R 中的抓取列表

c# - 通过 C# 中的属性检索嵌套 Powershell 对象的值