【问题标题】:In Python, I assigned an empty list to another list to print and for some reason it prints the last element of the list [closed]在 Python 中,我将一个空列表分配给另一个列表进行打印,并且由于某种原因它打印列表的最后一个元素 [关闭]
【发布时间】:2021-05-22 12:14:46
【问题描述】:

而不是打印 12359 由于某种原因它打印了 9

代码

  b=["12","3","5","9"]
  b1=[]
  for x in range(0,len(b)):
      b1=b[x]

  print(b1,end='')

输出

9

【问题讨论】:

  • 您还必须缩进 print(b1),因此它将在循环中执行。不过,这将在一行中打印每个数字。如果要将它们全部放在一行中,请将它们添加到输出字符串中。
  • 我是 python 新手,所以我不明白你的意思
  • b1=b[x] 具有相同缩进(代码前的空格数)的所有内容都将在循环内执行。要创建列表或字符串,请参阅我更详细的答案。
  • 这能回答你的问题吗? List append() in for loop

标签: python


【解决方案1】:

好吧,如果你想将 b 的元素连接成一个字符串, 试试看:

b = ["12", "3", "5", "9"]
b1 = ''.join(b)

解释:

Help on built-in function join:

join(iterable, /) method of builtins.str instance
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

【讨论】:

    【解决方案2】:

    b1 不是列表。它是一个字符串。如果你有一个列表,这样做:

     b=["12","3","5","9"]
      b1=[]
      for x in range(0,len(b)):
          b1.append(b[x])
    
    print(b1) # Prints the exact same as b.
    

    如果你想要一个输出字符串,你应该像这样将它添加到一个空字符串中:

     b=["12","3","5","9"]
      b1=""
      for x in range(0,len(b)):
          b1 += b[x]
    

    【讨论】:

      【解决方案3】:

      如果要连接所有字符串,需要使用b1的字符串:

      b = ["12", "3", "5", "9"]
      b1 = ""
      for x in range(0, len(b)):
          b1 += b[x]
      print(b1)
      

      【讨论】:

      • 那么为什么你使用 b1=" " 而不是 b1=[ ]?有什么原因吗?
      • 如果你想打印“12359”你需要一个字符串,而不是一个列表。
      猜你喜欢
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 2012-08-24
      • 2020-06-22
      • 2021-12-28
      • 2019-08-31
      • 2022-07-07
      • 2020-08-24
      相关资源
      最近更新 更多