简体   繁体   中英

Python - Best way to replace an element in a list with a key value from a dictionary

As the title says.
What's the best way to replace an element in a list, with a key value from a dictionary?

I have the following list: ['X', 'R', 'Y', 'F'] and the dictionary: ('X': ['X', 'R', 'Y', 'F']) I'd like to look through the list and replace each element which is equals to the key in the dictionary with the value in the dictionary.

lst = ['X', 'R', 'Y', 'F'] 
replacements = {'X': ['X', 'R', 'Y', 'F']}
new_lst = [replacements.get(i, i) for i in lst]
print new_lst     # [['X', 'R', 'Y', 'F'], 'R', 'Y', 'F']
# The input list
myList = ['X', 'R', 'Y', 'F']

# The input dictionary
myDict = {'X': ['X', 'R', 'Y', 'F']}

# Iterate through every element in the list
for iterator, element in enumerate(myList):
    # If the current element is present in the input dictionary
    if element in myDict.keys():
        # Replace the element
        myList[iterator] = myDict[element]

# Print the transformed list
print myList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM