【问题标题】:Convert a dynamically sized list to a f string将动态大小的列表转换为 f 字符串
【发布时间】:2022-12-24 01:05:56
【问题描述】:

我正在尝试获取一个大小为 1 或更大的列表,并将其转换为格式为 "val1, val2, val3 and val4" 的字符串,您可以在其中使用不同的列表长度,并且最后一个值的格式将在其前面加上一个和而不是逗号。

我当前的代码:

inputlist = ["val1", "val2", "val3"]
outputstr = ""
            for i in range(len(inputlist)-1):
                if i == len(inputlist)-1:
                    outputstr = outputstr + inputlist[i]
                elif i == len(inputlist)-2:
                    outputstr = f"{outputstr + inputlist[i]} and "
                else:
                    outputstr = f"{outputstr + inputlist[i]}, "
            print(f"Formatted list is: {outputstr}")

预期结果:

Formatted list is: val1, val2 and val3

【问题讨论】:

    标签: python list f-string


    【解决方案1】:

    join处理最多。

    for inputlist in [["1"], ["one", "two"], ["val1", "val2", "val3"]]:
        if len(inputlist) <= 1:
            outputstr = "".join(inputlist)
        else:
            outputstr = " and ".join([", ".join(inputlist[:-1]), inputlist[-1]])
        print(f"Formatted list is: {outputstr}")
    

    产品

    Formatted list is: 1
    Formatted list is: one and two
    Formatted list is: val1, val2 and val3
    

    【讨论】:

      【解决方案2】:

      决定改用字符串方法,而且效果很好。

      outputstr = str(inputlist).replace("'", "").strip("[]")[::-1].replace(",", " and"[::-1], 1)[::-1]
                  print(f"With the following codes enabled: {outputstr}")
      

      【讨论】:

      • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写出好的答案的信息in the help center
      【解决方案3】:

      python中的range函数不包括最后一个元素, 例如 range(5) 只给出 [0, 1, 2, 3, 4] 它不会在列表中添加 5(The official webiste),

      所以你的代码应该改成这样:

      inputlist = ["val1", "val2", "val3"]
      outputstr = ""
      
      for i in range(len(inputlist)):
          if i == len(inputlist)-1:
              outputstr = outputstr + inputlist[i]
          elif i == len(inputlist)-2:
              outputstr = f"{outputstr + inputlist[i]} and "
          else:
              outputstr = f"{outputstr + inputlist[i]}, "
      print(f"Formatted list is: {outputstr}")
      

      【讨论】:

      • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写出好的答案的信息in the help center
      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 2020-05-23
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多