Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在循环迭代时创建新的空列表?_Python - Fatal编程技术网

Python 在循环迭代时创建新的空列表?

Python 在循环迭代时创建新的空列表?,python,Python,因此,我觉得如果我更新空列表的名称,我可以使我的代码大大缩短,但我不知道我该怎么做?下面是它的常规外观。该程序的目的是按范围排序 x=[11,12,21,34,35,36] list_1020 = [] list_2030 = [] list_3040 = [] for i in x: if 10<= i <20: list_1020.append[i] x=[11,12,21,34,35,36] 列表_1020=[] 列表_2030=[] 列表_3040=[] 对于x

因此,我觉得如果我更新空列表的名称,我可以使我的代码大大缩短,但我不知道我该怎么做?下面是它的常规外观。该程序的目的是按范围排序

x=[11,12,21,34,35,36]

list_1020 = []
list_2030 = []
list_3040 = []

for i in x:
  if 10<= i <20:
  list_1020.append[i]
x=[11,12,21,34,35,36]
列表_1020=[]
列表_2030=[]
列表_3040=[]
对于x中的i:
如果10
现在,您的
列表
变量是一个字典,它将(最小、最大)对映射到该范围内的值列表:

>>> lists[(10, 20)]
[11, 12]
当然,您不需要在键中同时使用下限和上限-您可以只按下限存储它们,因为您知道范围有多宽: 导入集合

x=[11,12,21,34,35,36]

lists = collections.defaultdict(list)

for i in x:
    lower = (i//10) * 10
    lists[lower].append[i]

建立一个字典,然后你可以得到你想要的值

s = {}    
for i in x:
  s.setdefault((i+9)//10*10, []).append(i),
# {40: [34, 35, 36], 20: [11, 12], 30: [21]}

如果要使用
dict
这是一种解决方案:

x = [11, 12, 21, 35, 36]

bottom = 10
top = 10

ceiling = int(round(max(x), -1))

solution = {}

while top <= ceiling:
    solution['list_{}{}'.format(bottom, top)] = [i for i in x if bottom <= i < top]
    bottom += 10
    top += 10
x=[11,12,21,35,36]
底部=10
top=10
天花板=整数(圆形(最大(x),-1))
解决方案={}
top时,您可以始终使用按较低范围对排序的数字进行分组:

from itertools import groupby

x=[11,12,21,34,35,36]

grouped = [list(g) for _, g in groupby(x, key = lambda x: (x//10) * 10)]

print(grouped)
哪些产出:

[[11, 12], [21], [34, 35, 36]]
然后,您可以将这些列表插入字典:

ranges = ['list_1020', 'list_2030', 'list_3040']
d = dict(zip(ranges, grouped))
# {'list_1020': [10, 11, 12], 'list_2030': [21], 'list_3040': [34, 35, 36]}
甚至一行:

grouped = dict(('list_' + str(k) + str(k+10), list(g)) for k, g in groupby(x, key = lambda x: (x//10) * 10))
# {'list_1020': [10, 11, 12], 'list_2030': [21], 'list_3040': [34, 35, 36]}

也许您可以简单地使用
Python Dictionary
,因为您需要命名容器,其名称如下:
list\u 1020
list\u 2030
,等等。此外,这给了您一些空间,因为它将作为
字典键动态生成。下面是这个想法在代码中的表现:

listDict    = {}
x           = [11,12,21,34,35,36]

for q in range(10, 40, 10):
    tKey    = (q, (q+10))
    dictKey = "list_{}{}".format(tKey[0], tKey[1])
    listDict[dictKey] = [i for i in x if i in range(tKey[0], tKey[1]+1)]


print(listDict)
print(listDict["list_1020"])
print(listDict["list_2030"])
print(listDict["list_3040"])
作为可重用的功能:

def groupDataValues(x, minVal=10, maxVal=40, step=10):
    listDict    = {}
    for q in range(minVal, maxVal, step):
        tKey    = (q, (q+step))
        dictKey = "list_{}{}".format(tKey[0], tKey[1])
        listDict[dictKey] = [i for i in x if i in range(tKey[0], tKey[1]+1)]
    return listDict

x           = [11,12,21,34,35,36]
listDict    = groupDataValues(x, 10, 40, 10)

您可以通过从10,20,30中查找int的距离来执行类似操作

map_dict={10:'10-20',20:'20-30',30:'30-40'}



x=[11,12,21,34,35,36]

dict_1={}

for i in x:
    for b in map_dict.keys():
        if i not in dict_1:
            dict_1[i]=[(abs(i-b),b)]
        else:
            dict_1[i].append((abs(i-b),b))

final_output={}

for key,value in dict_1.items():
    if map_dict[min(value)[1]] not in final_output:
        final_output[map_dict[min(value)[1]]]=[key]
    else:
        final_output[map_dict[min(value)[1]]].append(key)

print(final_output)
输出:

{'20-30': [21], '10-20': [11, 12], '30-40': [34, 35, 36]}

你想干什么?Python不支持动态名称,如果您是这么想的话。请使用
defaultdict
来存储和访问列表。顺便说一句,对内置名称进行阴影处理是一个非常坏的习惯,例如
max
min
。您可以这样使用:
表示x中的i:(如果i<20,则列出\u 1020如果i<30,则列出\u 2030如果i<30,则列出\u 3040如果i<40,则无)。附加(i)
。但是,您可能希望使用字典进行适当的分组:
d={}
,x:d.setdefault(i//10,[]).append(i)
map_dict={10:'10-20',20:'20-30',30:'30-40'}



x=[11,12,21,34,35,36]

dict_1={}

for i in x:
    for b in map_dict.keys():
        if i not in dict_1:
            dict_1[i]=[(abs(i-b),b)]
        else:
            dict_1[i].append((abs(i-b),b))

final_output={}

for key,value in dict_1.items():
    if map_dict[min(value)[1]] not in final_output:
        final_output[map_dict[min(value)[1]]]=[key]
    else:
        final_output[map_dict[min(value)[1]]].append(key)

print(final_output)
{'20-30': [21], '10-20': [11, 12], '30-40': [34, 35, 36]}