简体   繁体   English

Python-打印不带方括号的函数中的数字列表

[英]Python - Print list of numbers from function without square brackets

I'm generating a list of random digits, but I'm struggling to figure out how to output the digits in a single row without the square brackets? 我正在生成一个随机数字列表,但是我正在努力弄清楚如何在没有方括号的情况下在一行中输出数字?

import random 
def generateAnswer(answerList):

    listofDigits = []
    while len(listofDigits) < 5:
        digit = random.randint(1, 9)
        if digit not in listofDigits:
            listofDigits.append(digit)
    return listofDigits

def main():
    listofDigits = []
    print(generateAnswer(listofDigits))

main()
print(", ".join([str(i) for i in generateAnswer(listofDigits)]))

您可以解压缩列表并使用sep参数:

print(*generateAnswer(listofDigits), sep=' ')

Try this: 尝试这个:

listofDigits = []
print(str(generateAnswer(listofDigits))[1:-1])

Also, if generateAnswer initialize and return the list, then you don't need to pass in an empty list. 另外,如果generateAnswer初始化并返回列表,则无需传递空列表。 Another thing is that if you want to generate a non-repeating random list, you can use random.sample and range . 另一件事是,如果要生成非重复的随机列表,则可以使用random.samplerange

I think this is better: 我认为这样更好:

import random 
def generateAnswer():
    return random.sample(range(1, 10), 5)

def main():
    print(str(generateAnswer())[1:-1])

main()

Hope it helps! 希望能帮助到你!

The reason you're getting the brackets is because the list class, by default, prints the brackets. 之所以得到括号,是因为list类默认情况下会打印括号。 To remove the brackets, either use a loop or string.join : 要除去括号,请使用循环或string.join

>>> print(' '.join(map(str, listofDigits)))
9 2 1 8 6
>>> for i in listofDigits:
    print(i, end=' ')


9 2 1 8 6 

Note that the last method adds a space at the end. 请注意,最后一种方法在末尾添加了一个空格。

Note that in the first method, the arguments need to be cast to strings because you can only join strings, not ints. 请注意,在第一种方法中,需要将参数强制转换为字符串,因为您只能join字符串,不能连接整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM