【问题标题】:Python Lists and Loops/Changing ElementsPython 列表和循环/更改元素
【发布时间】:2016-07-21 21:46:17
【问题描述】:

我创建了一个 while 循环(如下),它访问列表的每个元素并打印其正方形。现在,我将如何更改此程序,以便将每个元素替换为正方形。例如:如果 x = [2,4,2,6,8,10],则 x 将更改为 x = [4,16,4,36,4,64,100]

    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

【问题讨论】:

    标签: python list while-loop


    【解决方案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
    

    不过,使用eval() 不是一个好主意。你应该使用ast.literal_eval():

    import ast
    
    print("Enter any into the list: ")
    x = ast.literal_eval(input())
    ...
    

    【讨论】:

      【解决方案2】:

      除了for 循环之外,您几乎会做同样的事情:

      for i in range(0, len(x)):   # x must be a list
          x[i] **= 2   
      

      您也可以在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] **= 2
          n += 1
      

      【讨论】:

      • range() 不需要第一个参数。默认开始是0
      • 不知道...但我喜欢那里的 0 只是为了便于阅读
      • 如何创建列表的修改副本,以创建整数平方的新列表。换句话说,会有原始列表和带有正方形的新列表?
      【解决方案3】:
      x = [n**2 for n in x]
      

      列表推导是你的朋友。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 2012-08-31
        • 2020-08-08
        • 2014-01-03
        相关资源
        最近更新 更多