【问题标题】:create lists of unique names in a for -loop in python在 python 的 for 循环中创建唯一名称列表
【发布时间】:2013-01-27 00:13:58
【问题描述】:

我想在 for 循环中创建一系列具有唯一名称的列表,并使用索引来创建列表名称。这是我想做的事

x = [100,2,300,4,75]

for i in x:

  list_i=[]

我想创建空列表,例如

lst_100 = [], lst_2 =[] lst_300 = []..

有什么帮助吗?

【问题讨论】:

    标签: python list for-loop unique


    【解决方案1】:

    不要动态命名变量。这使得与他们一起编程变得很困难。相反,使用字典:

    x = [100,2,300,4,75]
    dct = {}
    for i in x:
        dct['lst_%s' % i] = []
    
    print(dct)
    # {'lst_300': [], 'lst_75': [], 'lst_100': [], 'lst_2': [], 'lst_4': []}
    

    【讨论】:

    • 有没有办法在保持原始x的顺序的同时做?相反,我在这里看到,在 root 的回答中,没有保留“100、2、300、4、75”的顺序。我想这是一些 dict 属性。
    • @Coolio2654:对。 dict 键未排序。要保留插入键的顺序,请使用collections.OrderedDict:(更改dct = {} --> import collections 后跟dct = collections.OrderedDict())。
    【解决方案2】:

    使用字典来保存您的列表:

    In [8]: x = [100,2,300,4,75]
    
    In [9]: {i:[] for i in x}
    Out[9]: {2: [], 4: [], 75: [], 100: [], 300: []}
    

    访问每个列表:

    In [10]: d = {i:[] for i in x}
    
    In [11]: d[75]
    Out[11]: []
    

    如果你真的想在每个标签中都有lst_

    In [13]: {'lst_{}'.format(i):[] for i in x}
    Out[13]: {'lst_100': [], 'lst_2': [], 'lst_300': [], 'lst_4': [], 'lst_75': []}
    

    【讨论】:

    • 这是我的第一个想法,你先去吧:P
    • @F3AR3DLEGEND -- 我认为这是最 Pythonic 的方式 :)
    • 这是字典理解吗? :-)
    【解决方案3】:

    与其他人的 dict-solutions 稍有不同的是使用 defaultdict。它允许您通过调用所选类型的默认值来跳过初始化步骤。

    在这种情况下,选择的类型是一个列表,它会在字典中为您提供空列表:

    >>> from collections import defaultdict
    >>> d = defaultdict(list)
    >>> d[100]
    []
    

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多