【问题标题】:How to get rid of comma at the end of printing from loop如何在循环打印结束时去掉逗号
【发布时间】:2022-11-22 01:18:43
【问题描述】:

所以基本上我有很多点的列表,我只想提取唯一值。 我写了一个函数,但有 1 个问题:如何避免在列表末尾打印逗号?

def unique(list1):
    unique_values = []
    for u in list1:
        if u not in unique_values:
            unique_values.append(u)
    for u in unique_values:
        print(u, end=", ")


wells = ["U1", "U1", "U3", "U3", "U3", "U5", "U5", "U5", "U7", "U7", "U7", "U7", "U7", "U8", "U8"]
print("The unique values from list are...:", end=" ")
unique(wells)

我现在的输出是:“列表中的唯一值是……:U1、U3、U5、U7、U8,”

【问题讨论】:

    标签: python


    【解决方案1】:

    代替:

    对于你在 unique_values 中:
            打印(你,结束=“,”)

    与蟒蛇:

    print(', '.join(unique_values))

    【讨论】:

      【解决方案2】:

      这可能有点矫枉过正,但您可以使用NumPy“独特”方法,这可能更有效,特别适用于大型数组或长列表。

      以下代码将执行:

      import numpy as np
      x = np.array(['a', 'a', 'b', 'c', 'd', 'd'])
      y = np.unique(x)
      print(', '.join(y))
      

      结果是:

      a, b, c, d
      

      【讨论】:

      • 您可以使用', '.join(set(values))。不需要麻木
      【解决方案3】:

      希望以下更改对您有所帮助 :)

      def unique(list1):
          unique_values = []
          for u in list1:
              if u not in unique_values:
                  unique_values.append(u)
          return unique_values
      
      
      wells = ["U1", "U1", "U3", "U3", "U3", "U5", "U5", "U5", "U7", "U7", "U7", "U7", "U7", "U8", "U8"]
      req = unique(wells)
      # prints in list format
      print(f"The unique values from list are...: {req}")
      # prints in string format
      print(f"The unique values from list are...: {' '.join(req)}")
      

      或者也可以使用set(wells)找到唯一值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 2013-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多