首页 > 解决方案 > 如何缩短代码以制作多个列表?

问题描述

我正在制作 12 个经过相同过程的列表。不幸的是,我不知道如何让它们都在一个循环中执行此操作,并且我不得不重复相同的代码 12 次并占用一大块文本。

这是我必须编写的代码的一小部分。

  l1 = []
  l1.append(random.choice(easy))
  if "none" in l1:
    l1.remove("none")
  else:
    psblnsrs.append(l1[0])
    easy.remove(l1[0])
  l1.append(random.choice(special))
  if "none" in l1:
    l1.remove("none")
  elif len(l1) >1:
    usblhks.append(l1[1])
  else:
    usblhks.append(l1[0])
  while sum(len(l1) for l1 in l1) < 12:
    l1.append(random.choice(junk))
  random.shuffle(l1)
  l2 = []
  l2.append(random.choice(easy))
  if "none" in l2:
    l2.remove("none")
  else:
    psblnsrs.append(l2[0])
    easy.remove(l2[0])
  l2.append(random.choice(special))
  if "none" in l2:
    l2.remove("none")
  elif len(l2) >1:
    usblhks.append(l2[1])
  else:
    usblhks.append(l2[0])
  while sum(len(l2) for l2 in l2) < 12:
    l2.append(random.choice(junk))
  random.shuffle(l2)

请记住,需要制作十二个列表,这只是两个

我不太熟悉编码大量循环和正确命名变量。我想要这样的东西:

for i in range(12):
  l(i) = []
  l(i).append ...

有没有办法使这项工作或类似的方式来使这项工作?

另外,如果代码难以理解,源材料在这里

标签: pythonlist

解决方案


函数可能会派上用场

def make_list(inp_list1=psblnsrs, inp_list2=usblhks, easy_list=easy, special_list=special, junk_list=junk):
    l1 = []
    l1.append(random.choice(easy_list))
    if "none" in l1:
      l1.remove("none")
    else:
      psblnsrs.append(l1[0])
      easy.remove(l1[0])
    l1.append(random.choice(special_list))
    if "none" in l1:
      l1.remove("none")
    elif len(l1) >1:
      usblhks.append(l1[1])
    else:
      usblhks.append(l1[0])
    while sum(len(l1) for l1 in l1) < 12:
      l1.append(random.choice(junk_list))
    return random.shuffule(l1)

l = []
for i in range(12):
  l.append(make_list())

推荐阅读