Python:有时打印整个数组而不是单个单词

时间:2018-06-12 14:03:34

标签: python arrays list append

对于Python来说还是比较新的,我现在只是在业余时间随机制作东西以帮助我学习。目前这就是我正在做的事情:

import sys
import random
import time
import pyperclip

print ('shit talk generator')
names = str(raw_input('Usernames: '))

splitNames = names.split(',')
splitNames.append(splitNames)


while True:   
    for x in range(1):
        iqValue = random.randint(-100,10000)
    randomName = random.choice(splitNames)
    print ('Wow %s, That was a %s IQ Play!' % (randomName, iqValue))
    clipboardCopy = 'Wow %s, That was a %s IQ Play!' % (randomName, iqValue)
    pyperclip.copy(clipboardCopy)
    print('waiting 2')
    time.sleep(2)

基本上,正如您已经收集的那样,只需生成狗屎说话并将其保存到剪贴板中。现在,有时在打印输出时,它会打印整个数组而不是单个单词。这是输出的片段:

shit talk generator
Usernames: lewis, daniel, james, john, jack, roger, fred, jones
Wow  john, That was a 1073 IQ Play!
waiting 2
Wow  roger, That was a 6182 IQ Play!
waiting 2
Wow  jack, That was a 3330 IQ Play!
waiting 2
Wow ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones', [...]], That was a 5734 IQ Play!
waiting 2
Wow ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones', [...]], That was a 4963 IQ Play!
waiting 2
Wow  fred, That was a 223 IQ Play!
waiting 2
Wow  james, That was a 7995 IQ Play!
waiting 2
Wow lewis, That was a 7620 IQ Play!
waiting 2

现在由于这是间歇性的,它让我相信它将整个自我存储在列表中的一个项目,我错误地假设这个?我如何解决这个问题并确保它只从输入中选择有效的用户名?非常感谢任何帮助/指导。

1 个答案:

答案 0 :(得分:1)

问题与你说的完全一样,罪魁祸首就是这里的代码:

splitNames = names.split(',')
splitNames.append(splitNames)

初始化splitNames后,您需要将其附加到自身。因此,在您的函数执行时,

splitNames = ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones', ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones']]

由于你的函数从列表中选择一个随机元素,它有时会选择最后一个元素,即列表本身。只需删除.append()行,您的代码就可以按照您的意愿运行。