我有一個字串 ( string = 'OBEQAMXITWA'),我想將它添加到一個空串列中,總是滿足一個條件。某個字母不應位于字串的確定位置,而應位于其他位置。例如,字母A不應位于該位置5,而應位于任何其他位置。如果滿足此條件,我將字串附加到串列中;如果沒有,我不附加它。
string = 'OBEQAMXITWA'
if 'A' != string[5] and ('A' in string[0:5] or 'A' in string[6:len(string)]):
word_list.append(string)
另一方面,我想檢查字母Z是否不在 position 6that is True,但我只會添加 if Zis in any other position that is not position 6。在這種情況下,Z不在字串中,所以我不會將它添加到串列中。
我想迭代地執行此操作,定義字典 ??( letter:position) 并檢查添加到字典中的所有字母和位置。例如,手動執行此操作的整個代碼將是這樣的:
string = 'OBEQAMXITWA'
word_list=[]
letter_change_pos = {'A':5,'T':3,'Z':6}
if 'A' != string[5] and ('A' in string[0:5] or 'A' in string[6:len(string)]):
word_list.append(string)
if 'T' != string[3] and ('T' in string[0:3] or 'T' in string[4:len(string)]):
word_list.append(string)
if 'Z' != string[6] and ('Z' in string[0:6] or 'Z' in string[7:len(string)]):
word_list.append(string)
print(word_list)
我怎么能使用for 回圈來做到這一點?
uj5u.com熱心網友回復:
該問題要求(1)回圈字典的每個字符,(2)檢查字符是否在字串中而不是在指定的索引中,(3)如果是,則將字串附加到串列中,以及(4)否則,不要附加字串。
使用回圈的快速解決方案可以是:
# The required string to check.
string = 'OBEQAMXITWA'
# Create an empty list.
wordList = []
# The dictionary rules for the string.
letterChangePos = {'A': 5, 'T': 3, 'Z': 6}
# Loop on each character of the dictionary.
for key in letterChangePos.keys():
# Check if the character is in the string.
if (key in string):
# Check if the key is not the same as the character in the specified index.
if (key != string[letterChangePos[key]]):
wordList.append(string)
# Print the list.
print(wordList)
使用綜合串列方法,解決方案將是:
# The required string to check.
string = 'OBEQAMXITWA'
# The dictionary rules for the string.
letterChangePos = {'A': 5, 'T': 3, 'Z': 6}
wordList = [
string for key in letterChangePos.keys()
if ((key in string) and (key != string[letterChangePos[key]]))
]
# Print the list.
print(wordList)
uj5u.com熱心網友回復:
def check_list(test_string, position_dict):
word_list = []
for key, value in position_dict.items():
if key != test_string[value - 1] and (key in string[0:value-1] or key in string[value:]):
word_list.append(test_string)
return word_list
if __name__ == '__main__':
string = 'OBEQAMXITWA'
letter_change_pos = {'A': 5, 'T': 3, 'Z': 6}
print(check_list(string, letter_change_pos))
uj5u.com熱心網友回復:
我不確定標題“使用字典的鍵和值進行迭代”與您的問題有什么關系。
您可以撰寫一個函式來檢查字串中的每個字符,如下所示:
def check_invalid_character_positions(string, invalid_positions):
for idx, char in enumerate(string):
if invalid_positions.get(char) == idx:
return False
# Now check that the characters in invalid_positions are present
# elsewhere in the string
return not set(invalid_positions).difference(string)
像這樣使用它:
>>> string = 'OBEQAMXITWA'
>>> invalid_positions = {'A': 5, 'T': 3, 'Z': 6}
>>> if check_invalid_character_positions(string, invalid_positions):
... word_list.append(string)
根據此評論,您也可以在技術上使用我認為的正則運算式來執行此操作,但這會更復雜。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488142.html
上一篇:將父子字典串列轉換為嵌套字典
下一篇:將串列轉換為包含專案的字典
