【问题标题】:How to create an array of alternating values inside a dictionary without numpy?如何在没有numpy的字典中创建一个交替值数组?
【发布时间】:2019-11-05 10:35:19
【问题描述】:

我有这本词典:

dict = {
    "A1": [round(f, prec) for vr in ex_vrs for f in vr.pos],
    "A2": []
      }

我希望 A2 有点像 "A2": [0,1,0,1, .... ] 长度 = len(A1)/3*2

有什么想法可以做到这一点吗?非常感谢

【问题讨论】:

    标签: python arrays dictionary


    【解决方案1】:

    试试下面的。

    # initialise the dictionary with the A1 entry
    dict = {"A1" : [round(f, prec) for vr in ex_vrs for f in vr.pos]}
    
    # Determine length of the alternating list for the A2 entry
    mylength = int(len(dict["A1"])/3*2)
    
    # Use mod operator to determine (un)even numbers for the alternating list
    dict["A2"] = [i % 2 for i in range(mylength + 1)]
    

    如果你想要字符串而不是数字来交替:

    # initialise the dictionary with the A1 entry
    dict = {"A1" : [round(f, prec) for vr in ex_vrs for f in vr.pos]}
    
    # Determine length of the alternating list for the A2 entry
    mylength = int(len(dict["A1"])/3*2)
    
    # Determine the two strings
    string1 = "A"
    string2 = "B"
    
    # Use mod operator to determine (un)even numbers for the alternating list
    dict["A2"] = [(string1 if i % 2 == 0 else string2) for i in range(mylength + 1)]
    

    【讨论】:

    • 谢谢,如果我必须在两个字符串而不是 0 和 1 之间交替,你会怎么做?
    【解决方案2】:

    假设你的 A2 长度是 10,那么你可以这样做:

    len = 10 # Length of A2
    rest = [i%2 for i in range(len) ]
    print (rest)
    
    # In case you want some other series of characters like ["a", "b", "a", "b" "a", "b" "a", "b" "a", "b" ]
    # then you can use if else condition
    rest = ["a" if i%2 == 0 else "b" for i in range(10) ]
    print (rest)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2017-06-24
      • 1970-01-01
      • 2018-06-10
      • 2020-04-02
      相关资源
      最近更新 更多