I currently have a bunch of lists defined something like below:
old_list = [1, 2, 3, 4, 5]
I'm currently replacing the first element of that list then placing the contents of the list into a dictionary (where the key is the old element 0 value) by doing the following:
old_value = old_list[0]
old_list[0] = 'new value'
test_dict[old_value] = old_list
I was wondering, is this the best way to accomplish this? I was wondering if there was a way to make this a bit more efficient with list comprehension so it could look something a bit more like this:
test_dict[old_list[0]] = [i for idx, i in enumerate(old_list) if '''relevant conditions to replace element 0''']
Here is one way to do it
Code
old_list = [1, 2, 3, 4, 5]
new_value = 'new'
test_dict = {}
test_dict[old_list[0]] = [new_value] + old_list[1:]
print(test_dict)
Output
{1: ['new', 2, 3, 4, 5]}
Generalised form
old_list = [1, 2, 3, 4, 5]
idx = 2
new_value = 'new'
test_dict = {}
test_dict[old_list[idx]] = old_list[:idx] + [new_value] + old_list[idx+1:]
print(test_dict)
Output
{3: [1, 2, 'new', 4, 5]}
A readable form can be achieved with unpacking:
head, *tail = old_list
# if test_dict already exists
test_dict[head] = ["new value"] + tail
# otherwise
test_dict = {head: ["new value"] + tail}
# {1: ['new value', 2, 3, 4, 5]}
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.