在一行中打印一个 int 列表 python3 [英] Printing an int list in a single line python3

查看:46
本文介绍了在一行中打印一个 int 列表 python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 python 的新手,我正在尝试在一行中扫描由空格分隔的多个数字(假设以1 2 3"为例),并将其添加到 int 列表中.我是通过使用做到的:

I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:

#gets the string 
string = input('Input numbers: ') 
#converts the string into an array of int, excluding the whitespaces
array = [int(s) for s in string.split()] 

显然它有效,因为当我输入1 2 3"并执行 print(array) 时,输出是:

Apparently it works, since when I type in '1 2 3' and do a print(array) the output is:

[1, 2, 3]

但我想把它打印成一行,没有括号,数字之间有一个空格,就像这样:

But I want to print it in a single line without the brackets, and with a space in between the numbers, like this:

1 2 3

我尝试过:

for i in array:
    print(array[i], end=" ")

但我收到一个错误:

2 3 回溯(最近一次调用最后一次):

2 3 Traceback (most recent call last):

print(array[i], end="")

print(array[i], end=" ")

IndexError: 列表索引超出范围

IndexError: list index out of range

如何在一行中打印整数列表(假设我的前两行代码是正确的),并且没有括号和逗号?

How can I print the list of ints (assuming my first two lines of code are right) in a single line, and without the brackets and commas?

推荐答案

你想说

for i in array:
    print(i, end=" ")

语法i in array 迭代列表的每个成员.因此,array[i] 试图访问 array[1]array[2]array[3],但最后一个越界(array 的索引为 0、1 和 2).

The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).

你可以用print(" ".join(map(str,array)))获得同样的效果.

You can get the same effect with print(" ".join(map(str,array))).

这篇关于在一行中打印一个 int 列表 python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆