python - 如何缩短代码以制作多个列表?
问题描述
我正在制作 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 ...
有没有办法使这项工作或类似的方式来使这项工作?
另外,如果代码难以理解,源材料在这里。
解决方案
函数可能会派上用场
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())
推荐阅读
- function - 从 DLL 中调用 DLL 函数的调用者
- sql-server-2016 - SQL Server 中的第一个字符替换
- sql - 如何在 ssms 中声明日期时间类型的变量
- android - Android:保存jpeg图像而不压缩
- r - 使用 R 中的 for 循环填充二项分布的数据框
- java - 如何编写一个spring boot jpa规范加入多个表
- react-native - 如何在不阻塞 UI 的情况下处理繁重的 API 请求
- nvidia-jetson - NVidia DeepStream 输出推理类不匹配 - “车辆类”
- email - 请求被拒绝,因为请求的一个或多个范围未经授权或已过期
- java - 正则表达式屏蔽多个电话号码(~),除了最后 4 位数字