Perhaps use this:
[a[i] for i in (1,2,5)]
# [11, 12, 15]
Answer from unutbu on Stack OverflowBest way of extracting elements from a list and assigning them to a variable?
python - Extract elements from list of lists - Stack Overflow
beautifulsoup - How to get_text from item retrieved using find_all ('tag', 'class')
I need help with summing every N elements in a list.
What is the fastest way to get one element from a Python list?
How do I extract elements from several lists at the same time?
Does slicing a Python list change the original list?
Videos
Hello! I have a list of numpy arrays and I want to create a separate variable for each of them so that I can combine them.
This is what I have. The mask_array variable is what contains the list of arrays:
for array in mask_arrays:
mask_one = (mask_arrays[0])
mask_two = (mask_arrays[1])
mask_three = (mask_arrays[2])
mask_four = (mask_arrays[3])
combined_arys = mask_one + mask_two + mask_three + mask_fourBut I don't always know the amount of arrays that will be in the list. Sometimes it's 4 like it is in the example, but sometimes it may be two or 0 (5 is the max)
Is there anyway I can extract the numpy arrays from the list and assign them to mask_one, mask_two, etc in a way that best follows python conventions? I looked this up on stack overflow, and it seems like it isn't good practice to create variables that can vary in number like this and that I should use a dictionary instead? Is there a better method of combining the arrays?
A list comprehension will cover this quite nicely.
data = [
["Test_1",
{"name": "Test_level_1", "value": 10},
{"name": "Test_level_1 again", "value": 15}],
["Test_2",
{"name": "Test_level_2", "value": 1},
{"name": "Test_level_2 again", "value": 5}]
]
desired_data = [
item['name']
for sublist in data
for item in sublist
if isinstance(item, dict)
]
Result:
['Test_level_1', 'Test_level_1 again', 'Test_level_2', 'Test_level_2 again']
Iterate over your list, with a nice unpacking and keep the value from "name"
values = [["Test_1", {"name":"Test_level_1", "value":10}, {"name":"Test_level_1 again", "value":15}],
["Test_2", {"name":"Test_level_2", "value":1}, {"name":"Test_level_2 again", "value":5}]]
result = []
for first, *others in values:
for other in others:
result.append(other["name"])