I have a 2 dim List where I need to create a new 2 dim List but only using certain elements form the original one:
The original list looks like this:
a = [['Volvo',100,200,300],['SAAB',10,20,30],['Ford',7,8,9]]
and I need to create a new 2 dimensional list that picks element 1 and 4 from the original list:
[['Volvo',300],['SAAB',30],['Ford',9]]
This is how I started building the solution but I don't understand how to create the new List? I don't think I can use append?
num_cols = len(a[0])
num_rows = len(a)
for i in range(num_rows)
elem_1 = a[i][0]
elem_2 = a[i][num_cols-1]
Or maybe something like this:
arr_2d=[]
for x in range(num_rows):
column_elements = []
for y in range(num_cols):
# Enter the all the values w.r.t to a particular column
column_elements.append(a[x][0])
column_elements.append(a[x][num_cols-1])
#Append the column to the array.
arr_2d.append(column_elements)
print(arr_2d)
CodePudding user response:
This solved my problem. many thanks for the help!
num_cols = len(a[0])
arr_2d=[]
for x in range(number_of_rows):
column_elements = []
column_elements.append(a[x][0])
column_elements.append(int(a[x][num_cols - 1]))
arr_2d.append(column_elements)
print(arr_2d)
CodePudding user response:
You want a new list. In which case a trivial list comprehension will help you - i.e., no explicit loop constructs required:
a = [['Volvo',100,200,300],['SAAB',10,20,30],['Ford',7,8,9]]
b = [[e[0], e[-1]] for e in a]
print(b)
Output:
[['Volvo', 300], ['SAAB', 30], ['Ford', 9]]
CodePudding user response:
This is your answer:
a = [['Volvo', 100, 200, 300], ['SAAB', 10, 20, 30], ['Ford', 7, 8, 9]]
final_list = []
for i in range(len(a)):
b = [a[i][0], a[i][-1]]
final_list.append(b)
print(final_list)
and it will print this:
[['Volvo', 300], ['SAAB', 30], ['Ford', 9]]
note:
- There is no
:
at the end offor
loop - Didn't add new variable to the list