如何以+1的方式在下划线后追加到字典值的第二个值



想象一下我有一本这样的字典:

barcodedict={"12_20":[10,15,20], "12_21":[5, "5_1","5_2",6]}

然后我有一个与日期相对应的数字,比如12_21,如果它不存在,我们将其附加到该日期的值上:

if 8 not in barcodedict["12_21"]:
barcodedict["12_21"].append(8)
{'12_20': [10, 15, 20], '12_21': [5, "5_1", "5_2", 6, 8]}

然而,如果这个数字已经存在于值列表中,我想将它添加到值列表中并添加一个额外的整数,该整数表示它是新出现的:

if 5 not in barcodedict["12_21"]:
barcodedict["12_21"].append(5)
else: #which is now the case
barcodedict["12_21"].append(5_(2+1))
Desired output:
{"12_20":[10,15,20], "12_21":[5, "5_1","5_2","5_3",6, 8]}

从第二个例子中可以看出,我不允许在列表编号中加下划线,它们会被删除(5_1变为51(。如何在最后一个数字上添加+1的新列表?我试着对它们进行迭代,然后对它们进行拆分,但这似乎不符合语法,也不起作用,因为下划线被忽略了。

编辑2022年7月19日上午10:46,

我发现了一种有点古怪的方法,但它似乎暂时有效:

placeholder=[]
for i in barcodedict["12_21"]:
if "5" in str(i):
try:
placeholder.append(str(i).split("_")[1])
except:
print("this is for the first 5 occurence, that has no _notation")
print(placeholder)
if len(placeholder) == 0 :
placeholder=[0]
occurence=max(list(map(int, placeholder)))+1
barcodedict["12_21"].append("5_"+occurence)
prints {'12_20': [10, 15, 20], '12_21': [5, '5_1', '5_2', 6, '5_3']}

对于请求的数字/字符串混合,可以使用:

if 5 not in barcodedict["12_21"]:
barcodedict["12_21"].append(5)
else: #which is now the case
i = 1
while True:
if f"5_{i}" not in barcodedict["12_21"]:
barcodedict["12_21"].append(f"5_{i}")
break
i += 1

这样使用的下划线不会显示在print中,因为它们是为了方便表示大数字而使用的,但在解释时不会这样显示。如果它们的显示方式很重要,则应该使用字符串操作;如果您想将它们实际用作数字,并且只想以方便的方式表示,则可以使用其他方式。

另一个解决方案:

def fancy_append(dct, key, val):
last_num = max(
(
int(s[1])
for v in dct[key]
if isinstance(v, str) and (s := v.split("_"))[0] == str(val)
),
default=0,
)
dct[key].append(f"{val}_{last_num+1}" if last_num > 0 else val)

barcodedict = {"12_20": [10, 15, 20], "12_21": [5, "5_1", "5_2", 6]}
fancy_append(barcodedict, "12_21", 5)
print(barcodedict)

打印:

{'12_20': [10, 15, 20], '12_21': [5, '5_1', '5_2', 6, '5_3']}

最新更新