Python列表和循环/更改元素

Python列表和循环/更改元素,python,list,while-loop,Python,List,While Loop,我已经创建了一个while循环(如下),它访问列表中的每个元素并打印其方块。现在,我如何修改这个程序,使它用它的平方替换每个元素。例如:如果x=[2,4,2,6,8,10],那么x将更改为x=[4,16,4,36,4,64100] print("Enter any into the list: ") x = eval(input()) n=0 while n < len(x): print("The square of", x[n], "is

我已经创建了一个while循环(如下),它访问列表中的每个元素并打印其方块。现在,我如何修改这个程序,使它用它的平方替换每个元素。例如:如果x=[2,4,2,6,8,10],那么x将更改为x=[4,16,4,36,4,64100]

    print("Enter any into the list: ")
    x = eval(input())
    n=0
    while n < len(x):
        print("The square of", x[n], "is", x[n]**2)
        n += 1
print(“在列表中输入任何内容:”)
x=eval(输入())
n=0
当n
您可以在
循环时设置它:

print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] = x[n] ** 2
    n += 1
for i in range(0, len(x)):   # x must be a list
    x[i] **= 2   
print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] **= 2
    n += 1

除了使用
for
循环外,您几乎可以执行相同的操作:

print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] = x[n] ** 2
    n += 1
for i in range(0, len(x)):   # x must be a list
    x[i] **= 2   
print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] **= 2
    n += 1
您还可以在
while
循环中设置它:

print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] = x[n] ** 2
    n += 1
for i in range(0, len(x)):   # x must be a list
    x[i] **= 2   
print("Enter any into the list: ")
x = eval(input())
n=0
while n < len(x):
    print("The square of", x[n], "is", x[n]**2)
    x[n] **= 2
    n += 1
print(“在列表中输入任何内容:”)
x=eval(输入())
n=0
当n

列表理解是您的朋友。

range()
不需要第一个参数。默认开始是
0
。不知道。。。但我喜欢那里的0,只是为了可读性。我如何创建列表的修改副本,以创建整数平方的新列表。换句话说,将有一个原始列表和一个带有正方形的新列表?