【发布时间】: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
我有这本词典:
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
试试下面的。
# 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)]
【讨论】:
假设你的 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)
【讨论】: