<p>您的代码需要大量修改才能工作:</p>
<pre><code>if firstb == "Item":
S = []
l = len(S)
while l < rarPropTotal:
c = random.choice([Propstr, Weightstr])
S.append(c)
d = random.choice([Propstr, Weightstr])
while d == c:
d = random.choice([Propstr, Weightstr])
S.append(d)
l = l + 1
print("Property List: " + str(S))
</code></pre>
<p>为了解释,首先我在外部while循环的末尾添加了递增<code>l</code>的终止条件。然后我将调用改为<code>random.choice</code>,从变量列表中进行选择。然后我重写了如何检查重复项,因为您最初的方法根本没有这样做。<code>c</code>总是在<code>S</code>列表中,因为您将它添加到了那里。打印时还需要将<code>S</code>列表转换为字符串。你知道吗</p>
<p>对数据运行上述代码时的输出示例:</p>
<pre><code>> Type: Item
> Total: 3
> Item Type: Head
Property List: ['[1, 0.5, 0.25]', "['Stat1', 'Stat2', 'Stat3']", "['Stat1', 'Stat2', 'Stat3']", '[1, 0.5, 0.25]', '[1, 0.5, 0.25]', "['Stat1', 'Stat2', 'Stat3']"]
</code></pre>
<p><strong>编辑:</strong>根据您的评论,我认为您应该这样做:</p>
<pre><code>if firstb == "Item":
S = []
l = len(S)
while l < rarPropTotal:
c = random.choices(PropRoll, PropWeight)[0] #[0] to avoid nested lists
if c not in S:
S.append(c)
l = l + 1
print("Property List: " + str(S))
</code></pre>
<p>这样可以确保没有重复项。主要的变化是它不再像在原始代码中那样使用字符串了,因为不能对编码为字符串的列表执行<code>random.choice</code>。这就是为什么它使用你的<code>PropRoll</code>和<code>PropWeight</code>。另一件事是,如果你想使用权重,你必须使用<code>choices()</code>方法,而不是<code>choice()</code>。<a href="https://docs.python.org/dev/library/random.html#random.choices" rel="nofollow noreferrer">former</a>可以使用权重,后者不能。你知道吗</p>
<p>样本输出:</p>
<pre><code>> Type: Item
> Total: 2
> Item Type: Head
Property List: ['Stat1', 'Stat3']
</code></pre>