我有這本詞典:
{128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
我想確保每個鍵都只有一個值“F”和一個值“S”,如果不是這樣,則回傳一條訊息
我試過了,但似乎沒有用:它沒有列印訊息
for key in d:
if not re.search(r"[F]{1}","".join(d[key])) or not re.search(r"[S].{1}","".join(d[key])):
print(f"There is no start or end stop for the line {key}.")
謝謝
uj5u.com熱心網友回復:
您的字典包含一個串列,而不是一個字串,因此您不應使用正則運算式。您可以檢查串列是否包含您想要使用的值的數量list.count(value)。
for key in d:
if not (d[?ey].count('F') == 1 and d[?ey].count('S') == 1):
print(f"There is no start or end stop for the line {key}.")
uj5u.com熱心網友回復:
您可以檢查每個值中這些字符的數量。一種方法如下
sample = {128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
wrong_lines = [index for index, value in sample.items() if value.count('S') == value.count('F') == 1]
print(f"Wrong lines {wrong_lines}")
uj5u.com熱心網友回復:
d = {128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
for key in d:
if not (d[key].count('F') == 1 and d[key].count('S') == 1):
print(f"There is no start or end stop for the line {key}.")
uj5u.com熱心網友回復:
您可以使用計數器并同時獲取所有字母的計數:
>>> from collections import Counter
>>> di={128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
>>> {k:Counter(v) for k,v in di.items()}
{128: Counter({'S': 2, 'O': 1, 'F': 1}), 512: Counter({'S': 1, 'F': 1})}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365741.html
