Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 以下代码的含义是什么?_Python_Python 3.x_List - Fatal编程技术网

Python 以下代码的含义是什么?

Python 以下代码的含义是什么?,python,python-3.x,list,Python,Python 3.x,List,问题是将4个整数作为输入,输入到单独的行中。 例:= 下面的代码执行所需的操作。我试图理解它的工作部分 x,y,z,n=[int(input()) for _ in range(4)] for uuu.范围(4)重复int(input())4次,因此括号中现在包含前四个输入[1,1,1,2] 在Python中,您可以一次分配多个变量,因此x、y、z和n将被分配给括号中相应的值 为了更好地理解,您可以提取如下各个部分: x = int(input()) y = int(input()) z =

问题是将4个整数作为输入,输入到单独的行中。 例:=

下面的代码执行所需的操作。我试图理解它的工作部分

x,y,z,n=[int(input()) for _ in range(4)]
for uuu.范围(4)
重复
int(input())
4次,因此括号中现在包含前四个输入
[1,1,1,2]

在Python中,您可以一次分配多个变量,因此x、y、z和n将被分配给括号中相应的值

为了更好地理解,您可以提取如下各个部分:

x = int(input())
y = int(input())
z = int(input())
n = int(input())
numbers_til_5 = [0,1,2,3,4,5]
squares_til_5 = []
for n in numbers_til_5:
  squares_til_5.append(n*n)

它运行一个循环,将值作为整数输入,并按该顺序将这些值传递给变量x、y、z、n。范围(n)在0-n范围内运行循环(在本例中为4次)。\u用于在运行循环时表示“任何东西”。

欢迎

此代码相当于

x = int(input())
y = int(input())
z = int(input())
n = int(input())
input()
函数读取用户的输入,而
int
尝试将其转换为一个整数,该整数被分配给每个变量(
x
y
z
n

代码也可以写成:

numbers = []
for i in range(4): # Loop 4 times
 numbers[i] = int(input())

x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
这与您提供的表格更相似。但是作者使用了两个python特性,使代码更小(更具表现力)。我将解释这两个方面:

  • 在编程过程中,您常常需要多次执行命令并将结果放入列表中,例如,将值从一个列表映射到另一个列表。在这种情况下,您将有如下内容:

    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    numbers_til_5 = [0,1,2,3,4,5]
    squares_til_5 = []
    for n in numbers_til_5:
      squares_til_5.append(n*n)
    
    通过列表理解语法,我们可以:

    sqaures_til_5 = [ n*n for n in numbers_til_5]
    
    另一个特点是:

  • 这是一个允许您在一条语句中获取列表元素的功能。 在本例中,我们有:

    x = numbers[0]
    y = numbers[1]
    z = numbers[2]
    n = numbers[3]
    
    可以用
    x,y,z,n=number
    替换。 另一种有趣的形式是,当您只关心第一个参数时,例如:

    first = numbers[0]
    rest = numbers[1:] # This get all elements starting from the first
    
    可以先写为
    ,*rest=numbers


    我希望我能说清楚。

    你到底不明白什么?我们是否需要解释
    input()
    <代码>int()<代码>范围()?列出理解?解包作业?对不起,我是Python初学者。非常感谢。这很有帮助。