Python3 帮助确定动态创建列表的大多数 pythonic 方法

标签 python python-3.x list-comprehension

向这里的专家寻求帮助,以帮助在我正在创建的程序中做出正确的选择。两种创建列表的方法中哪一种对您来说更像 Pythonic 和可读性更强?还是有更好的方法可以做到这一点?

方法 #1 - 列表理解

def test_func(*args):
    s = 'Country name: United {nm}'
    l = [s.format(nm='States') if x is 'us' 
         else s.format(nm='Arab Emirates') if x is 'uae'
         else s.format(nm='Kingdom') if x is 'uk' 
         else 'Unknown' for x in args]
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']

方法 #2 - for 循环

def test_func(*args):
    s = 'Country name: United {nm}'
    l = []
    for arg in args:
        if arg is 'us':
            l.append(s.format(nm='States'))
        elif arg is 'uk':
            l.append(s.format(nm='Kingdom'))
        elif arg is 'uae':
            l.append(s.format(nm='Arab Emirates'))
        else:
            l.append(s.format(nm='Unknown'))
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']

最佳答案

您在错误的级别进行映射。使用像这样的字典:

代码:

def test_func(*args):
    mapping = {
        'us': 'United States',
        'uae': 'United Arab Emirates',
        'uk': 'United Kingdom',
    }
    return ['Country name: {}'.format(mapping.get(x, 'Unknown')) for x in args]

# execute
print(test_func('us', 'uk', 'uae', 'xyzzy'))

结果:

[
    'Country name: United States', 
    'Country name: United Kingdom', 
    'Country name: United Arab Emirates',
    'Country name: Unknown'
]

关于Python3 帮助确定动态创建列表的大多数 pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107592/

相关文章:

python - 我们可以在模块中使用完全限定标识符而不导入模块吗?

python - MNIST 和 SGDClassifier 分类器

python - 按计数迭代计数器中的项目

python-3.x - 如何在 WSL2 上的 Ubuntu 中安装 cuDNN?

python - 列表推导式中定义的变量是否会泄漏到封闭范围中?

python - 列表理解无用变量

Python:将列表理解为 x,y 列表

python - 使用 modelformset_factory 时如何区分 django 中的表单集?

python - 有没有一种优雅的方法可以将组值重新映射到 pandas DataFrame 中的增量系列中?

python - 如何在字典列表中添加新的 key 对而不修改实际的字典列表?