【问题标题】:Finding the index of an element in a list when there are duplicates in python当python中有重复项时查找列表中元素的索引
【发布时间】:2022-11-26 14:24:53
【问题描述】:

所以对于上下文,有一个流行的问题叫做“斐波那契时钟”。本质上,您有一个颜色列表,例如 ["white","blue","re​​d","green","white"]。列表中的第一项的值为 1,然后第二项的值再次为 1,第三项的值为 2,第四项的值为 3,第五项的值为 5。 [1 ,1,2,3,5]。要查找 ["white","blue","re​​d","green","white"] 的时间,您可以将 Red 和 Blue 的值相加以获得小时,然后执行 5*(Green + Blue)分钟。在这种情况下,蓝色在第二个框中,表示它的值为 1,红色值在第三个框中,表示它的值为 2。所以 1 + 2 = 3,所以小时是3. 分钟为 5*(G + B),绿色在第 4 个位置,值为 3,蓝色在第二个位置,值为 1。 5(3 + 1) = 5(4 ) = 20。所以时间是 3:20。

所以我正在尝试为此编写一个程序,但我遇到了问题。红色、绿色和蓝色可以重复。例如,["Red","Red","Blue","Green","White]。在这种情况下,当添加 Red 和 Blue 时,您必须同时添加 Red 和 Blue 的值。这就是我对如何编码感到困惑。

这是我的代码:

x = [1,1,2,3,5]
y = []
r = []
for t in range(1,6,1):
    print("give me a color")
    s = input()
    y.append(s)

if "r" in y:
    if "b" in y:
        if "g" in y:
            r_index = y.index("r")
            r_index2 = y.index("b")
            r_index3 = y.index("g")
            r.append(r_index)
            r.append(r_index2)

            
if r_index == 0:
    r_index = 1
if r_index == 4:
    r_index = 5
if r_index2 == 0:
    r_index2 = 1
if r_index2 == 4:
    r_index2 = 5
hour = int(r_index) + int(r_index2)
minute = 5*(r_index2 + r_index3)
print("The final time is",hour,":",minute)

如果有重复的红色、绿色或蓝色,我的代码只会添加最小的值,从而导致错误的时间。

我将不胜感激关于如何解决这个问题的答案,以及一个固定的代码

【问题讨论】:

    标签: python list indexing duplicates


    【解决方案1】:
    fib = [
        1,
        1,
        2,
        3,
        5
    ]
    
    colors = [
        "red",
        "red",
        "blue",
        "green",
        "white"
    ]
    
    def get_sum_for(color):
        return sum(f for f, c in zip(fib, colors) if c == color)
    
    hours = get_sum_for("red") + get_sum_for("blue")
    minutes = 5 * (get_sum_for("green") + get_sum_for("blue"))
    
    print(f"{hours}:{minutes}")
    

    【讨论】:

      【解决方案2】:

      你可以只放入一个带有索引的 dic:

      from collections import defaultdict
      
      def get_hour(hour):
          fib_val = [1,1,2,3,5]
          fib = defaultdict(list)
          for idx, h in enumerate(hour):
              fib[h.lower()].append(fib_val[idx])
              
          h = sum(fib['red']  + fib['blue'])
          m = 5 * sum(fib['green']  + fib['blue'])
          return f"{h:02d}:{m:02d}"
      

      【讨论】:

        猜你喜欢
        • 2019-12-31
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 2023-03-13
        • 2011-05-05
        • 2015-01-11
        • 2017-12-01
        相关资源
        最近更新 更多