我正在尝试按如下方式创建数据结构:
import random
class Person:
DNA = [[{}] * 100] * 10 # 10 chromosomes, 100 genes in each?
def __init__(self):
DNA = Persona.DNA
# Generate random variables to create DNA
for chromosome, _ in DNA:
for gene, _ in chromosome:
if random.randint(0, 3) == 3:
DNA[chromosome][gene]['Str'] = 3
self.DNA = DNA
我收到了错误," ValueError:解压缩的值太多(预期2)"但我不明白我做错了什么。为什么我不能枚举?
答案 0 :(得分:5)
应用所有@ Jean-Francois的建议:
import random
class Person:
def __init__(self):
DNA = [[dict() for _ in range(100)] for _ in range(10)]
# Generate random variables to create DNA
for chromosome in DNA:
for gene in chromosome:
if random.randint(0, 3) == 3:
gene['Str'] = 3
self.DNA = DNA
或者,更简洁:
class Person:
def __init__(self):
self.DNA = [[dict(Str=3) if random.randint(0,3) == 3 else dict()
for _ in range(100)]
for _ in range(10)]
代码的主要问题是:
(idx, item)
元组,请使用enumerate
。例如,for i, chromosome in enumerate(DNA):
。否则,在列表上循环只会产生该列表中的项目。