简体   繁体   中英

Create list in Python based on two other lists?

I have a list which looks like this:

working_list=['one', 'two', 'three', 'four', 'five']

And I want to have a new list which would look like this:

output_list=['one or two','one or two','three','four or five','four or five']

For that, I have created two other lists:

old_names=[['one','two'],['four','five']]
new_names=['one or two','four or five']

And then I tried:

output_list=[]
for item in working_list:
  for a_list in old_names:
    if item in a_list:
        index=old_names.index(a_list)
        new_name=new_names[index]
        output_list.append(new_name)
    else:
        output_list.append(item) 
print(output_list)

But that gives me an output:

['one or two', 'one', 'one or two', 'two', 'three', 'three', 'four', 'four or five', 'five', 'four or five']

Any ideas on how to solve this?

Would greatly appreciate it!

For any kind of a->b mapping you should use a dictionary. For example, replace your old_names and new_names lists with an old_to_new_names dictionary

working_list = ['one', 'two', 'three', 'four', 'five']

old_to_new_names = {
    "one": "one or two",
    "two": "one or two",
    "four": "four or five",
    "five": "four or five",
}
output_list = [old_to_new_names.get(i, i) for i in working_list]

The old_to_new_names.get method looks for i in the dictionary and if it doesn't exist just returns i (the second argument is the default)

If you would still like to use your code with little modification but @tomjn is scalable and the best method

working_list=['one', 'two', 'three', 'four', 'five']
new_names=['one or two','four or five']
output_list = []
for item in working_list:
    found = False
    for check in new_names:
        print(item)
        if check.find(item) >= 0:
            found = True
            output_list.append(check)
            break
        else:
            continue
    if found == False:
        output_list.append(item)
print(output_list)

The answer by @tomjin is a better idea, the code with dicts is clear and easy to read, but if you want to know how your code could be tweaked to work:

All you need to do is check if an item from the working list exists in the string of the new names and if so, add the new name instead of it to the output list.

But you need to also check if you have already added something to the output list in the item's place, so you keep track of it with a bool and if and only if you checked all the new_names and you added nothing, you add it to the output list.

 for item in working_list
    added = False
        for new in new_names:
            if item in new
            output_list.append(new)
            added = True
    if not added
        output_list.append(item)

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