python - 如何在Python中一行输入数组及其长度

标签 python arrays input

我想将输入作为

3 10 20 30 

即n个数组元素

我试过了-

n , arr = int(input()), list(map(int(input).split()[:n]))

它显示错误,因为n未定义

最佳答案

考虑一下 Python 如何解释你的语句:

  1. 它计算 r 值(赋值的右侧部分),它是一个元组,然后
  2. 将该元组分配给左值:(n, arr)

但在第 1 步中,它遇到了一个未知的数量:n

因此,您应该这样做(并假设 s = '3 10 20 30',因为隐藏内置函数 input()< 并不是一个好主意):

arr = [int(x) for x in s.split()]
n = len(arr)  # if you really need it

编辑

有人指出,预期结果可能是n: 3arr: [10, 20, 30]。如果确实如此:

n, *arr = [int(x) for x in s.split()]

关于python - 如何在Python中一行输入数组及其长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66491985/

相关文章:

python - python中的屏幕共享

python - 在 Python 中使用 caffe.NetSpec() 时,train.prototxt 中的两个顶部 blob

javascript - 搜索对象数组(两个属性)以查找多个限制

reactjs - react - 警告 : ComponentXXX is changing an uncontrolled input of type undefined to be controlled

python - Mysql中的计算

python - 显示每个节点的 Neurolabs 权重/偏差?

c++ - arduino为多维数组赋值

c# - 字符串到数组,按第三个字/列排序

html - 在 Html Textarea 中设置最大长度

c++ - 使用 istringstream 的问题