【问题标题】:Convert string list of heights into centimeters将高度字符串列表转换为厘米
【发布时间】:2022-09-23 21:58:34
【问题描述】:

如何遍历高度字符串列表并将值转换为厘米?高度的格式如下:[\'5\\\' 11\"\', \'6\\\' 1\"\', \'6\\\' 3\"\']

我知道我将不得不对英尺和英寸的值进行切片并将它们转换为整数,但我不明白如何将这些值从列表中切出。例如,如果我使用 height[0],我将返回字符串 5\' 11\"。我怎样才能简单地返回 5 和 11 并遍历整个列表?

  • [5\' 11\", 6\' 1\", 6\' 3\"] 不是有效列表。
  • ` [5\' 11\", 6\' 1\", 6\' 3\"]` 不是有效列表。
  • 你是说[5\' 11\", 6\' 1\", 6\' 3\"] 是一个字符串吗?

标签: python


【解决方案1】:

如果字符串总是以相同的顺序同时具有英尺和英寸,则一种选择:

l = ['5\' 11"', '6\' 1"', '6\' 3"']

out = [int(ft[:-1])*30.48+int(inch[:-1])*2.54
       for s in l for ft, inch in [s.split()]]

输出[180.34, 185.42, 190.5]

【讨论】:

    【解决方案2】:

    对于列表中的每个元素,您可以省略最后一个字符并在' 上拆分以获得英尺和英寸。然后将int 映射到两者并转换为厘米

    heights = ["5' 11\"", "6' 1\"", "6' 3\""]
    
    
    def feet_inches_to_cm(feet, inches):
        return feet * 30.48 + inches * 2.54
    
    
    for height in heights:
        feet, inches = map(int, height[:-1].split("' "))
        print(feet_inches_to_cm(feet, inches))
    

    【讨论】:

      【解决方案3】:

      嘿有趣的问题:), 那个怎么样?

      def imperial_str_to_tuple(imp: str) -> tuple[int,int]:
          clean_str = imp.replace("'", "")  # 6' 1'' -> "6 1"
          number_list = map(int, clean_str.split(" "))  # -> 6,1
          return tuple(number_list)
      
      input_list = ["5' 11''", "6' 1''", "6' 3''"]
      splitted = [
          imperial_str_to_tuple(x)
          for x in input_list
      ]
      # should be now: [(5, 11), (6,1), (6,3)]
      
      # keep in mind to create your imperial2metric function
      result = [imperial2metric(t) for t in splitted]
      

      【讨论】:

        猜你喜欢
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-04
        • 1970-01-01
        • 1970-01-01
        • 2020-03-21
        相关资源
        最近更新 更多