例如,如果我有一个名为num
的用户输入:
num = int(input('Enter numbers'))
我希望能够将这些数字存储到要操作的列表中。 我怎么能这样做?感谢。
答案 0 :(得分:1)
提示"输入数字"建议用户在一行中输入多个数字,然后拆分该行并将每个数字转换为int
。这种列表理解是一种方便的方法:
numbers = [int(n) for n in input('Enter numbers: ').split()]
以上是针对Python 3.对于Python 2,请改为使用raw_input()
:
numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
在任何一种情况下:
>>> numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
Enter numbers: 1 2 3 4 5
>>> numbers
[1, 2, 3, 4, 5]
答案 1 :(得分:0)
input_numbers = raw_input("Enter numbers divided by spaces")
input_numbers_list = [int(n) for n in input_numbers.split()]
print input_numbers_list
答案 2 :(得分:0)
你可以通过使用名为map的
的python函数式编程结构在一行中完成python2
input_list = map(int, raw_input().split())
python3
input_list = map(int, input().split())
答案 3 :(得分:0)
输入:
bool main_init(int argc, char *argv[])
{
// if url protocol
if (strstr(argv[1], "protocol:") != NULL)
{
//decode and remove protocol.
char *decoded = url_decode(argv[1])+9;
// wrap " around original argv[0] and prepend to argv[1]
LPSTR buf[1024];
strcpy(buf, "\"");
strcat(buf, argv[0]);
strcat(buf, "\" ");
strcat(buf, decoded);
// ANSi version of CommandLineToArgvW: http://alter.org.ua/docs/win/args/
argv = CommandLineToArgvA(buf, &argc);
// argv appears correct at this point
}
// protocol causes crash here
int c = getopt_long(argc, argv, optstring, opts, NULL);
}
输出:
list_of_inputs = input("Write numbers: ").split()
#.split() will split the inputted numbers and convert it into a list
list_of_inputs= list(map(int , list_of_inputs))
#as the inputted numbers will be saved as a string. This code will convert the string into integers
我正在使用python 3.6