【问题标题】:Python - Can you use list comprehension to replace the value at a particular list index?Python - 您可以使用列表推导来替换特定列表索引处的值吗?
【发布时间】:2021-08-19 14:35:08
【问题描述】:

我目前有一堆列表定义如下:

old_list = [1, 2, 3, 4, 5]

我目前正在替换该列表的第一个元素,然后通过执行以下操作将列表的内容放入字典(其中键是旧元素 0 值):

old_value = old_list[0]    
old_list[0] = 'new value'
test_dict[old_value] = old_list

我想知道,这是实现这一目标的最佳方式吗?我想知道是否有一种方法可以通过列表理解来提高效率,使其看起来更像这样:

test_dict[old_list[0]] = [i for idx, i in enumerate(old_list) if '''relevant conditions to replace element 0''']

【问题讨论】:

  • 如果我给你指点dict comprehensions,你能找到解决办法吗? (不过,您需要一种方法来遍历old_lists)
  • 我会说您的原始方法很好,尽管使用列表组合绝对可以。 test_dict[old_list[0]] = ['newvalue' if idx == 0 else i for idx, i in enumerate(old_list)]
  • 试试:[i if idx != 0 else "new_value" for idx, i in enumerate(old_list)]
  • 不过,列表推导会构建一个新列表,而不是简单地就地替换原始元素中的一个元素。
  • @user3153443 请记住,列表理解并不是最节省内存(和时间效率)的解决方案。简单地替换一个元素会更有效

标签: python list replace list-comprehension element


【解决方案1】:

这是一种方法

代码

old_list = [1, 2, 3, 4, 5]
new_value = 'new'
test_dict = {}
test_dict[old_list[0]] = [new_value] + old_list[1:]
print(test_dict)

输出

{1: ['new', 2, 3, 4, 5]}

广义形式

old_list = [1, 2, 3, 4, 5]
idx = 2
new_value = 'new'
test_dict = {}

test_dict[old_list[idx]] = old_list[:idx] + [new_value] + old_list[idx+1:]
print(test_dict)

输出

{3: [1, 2, 'new', 4, 5]}

【讨论】:

    【解决方案2】:

    可以通过解包实现可读的形式:

    head, *tail = old_list
    
    # if test_dict already exists
    test_dict[head] = ["new value"] + tail
    
    # otherwise
    test_dict = {head: ["new value"] + tail}
    # {1: ['new value', 2, 3, 4, 5]}
    

    【讨论】:

    • 如果test_dict已经存在,则不一样。
    • 其实没什么大不了的,我个人认为是为了灵感就可以了,任何人都不应该在不了解它的作用的情况下逐字逐句地复制它。
    猜你喜欢
    • 2011-11-06
    • 2020-10-16
    • 2015-10-14
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多