How to get n element from the python list? - python

I have the following arrays:
a=[1,2,3,4]
b=['car','apple','orange']
I'm trying to iterate through arrays using:
for first,second in zip(a,b):
print(first,second)
But it prints all of the values at at time. How can I print 1st element from a array and 1st element from b array and so on?

You can use the [] operator to print the nth element of any array.
We can use a for loop to achieve a constant n value like this:
for i in range(3):
print(a[i], b[i])
Replace 3 with the length of both arrays, as the length should be the same.

You have two lists of differing lengths. Therefore, in order to access the values in pairs you could (probably should) use the zip() function.
If you don't want to use zip() then you need to start by determining the length of the shortest list then you can safely iterate over them. Something like this:
a = [1, 2, 3, 4]
b = ['car', 'apple', 'orange']
for k in range(len(min(a, b, key=len))):
print(a[k], b[k])
Output:
1 car
2 apple
3 orange

Related

Python find indexwise maximum average minimum for list of 100 sublists

I have a list containing 100+ sublists. Need to get index wise maximum for this scenario using python.
L1= [3,2,7]
L2= [1,5,7]
L3= [10,3,6]
Get max value from index 0 of all lists
Get min value from index 1 of all lists
Get avg value from index 2 of all lists
Result list is [10,2,6.666]
I don't have further code, there are at least 100 such lists for which this calculation is required
I can share with you one approach
let us say there are only 2 lists .. you should try to extend this logic to 100 lists
L1: [2,8, 1]
L2: [3, 1, 6]
so the answer will be
[3,8,6]
to solve this make a list which will store the answer
ans = [0,0,0]
now iterate over every list and just replace every index with the largest value you see at that index
after first list ans will look like
[2,8,1]
coz all values are greater than zero
when you iterate over 2nd list , 3 is greater than 2 and 6 is greater than 1 so you just update them
and your answer will become
[3,8,6]
Pretty simple: https://numpy.org/
Transform your list of lists "LoL" into an array...
import numpy as np
LoL = np.asarray([L1, L2, L3])
...and then apply those aggregations...
Check the docs for details. E.g., "max": https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html#numpy.ndarray.max
using zip():
Code:
L1= [3,2,7]
L2= [1,5,7]
L3= [10,3,6]
counter=0
res=[]
for lis in zip(L1,L2,L3): #It brings same index element together in the form of tuples [i.e (3, 1, 10),(2, 5, 3),(7, 7, 6)]
if counter==0:
res.append(max(lis))
counter+=1
elif counter==1:
res.append(min(lis))
counter+=1
else:
res.append(sum(lis)/len(lis)) #mean=sum_of_all_element/total_number_of_element
print(res) #Output [10, 2, 6.666666666666667]

Get indices of top N values from list in the order of the values

I have a list like a=[3,5,7,12,4,1,5] and need to get the indices of the top K(=3) elements of this list, in the order of the elements. So in this case, result should be
[3,2,1]
since top 3 elements are 12, 7, 5 (last one is tie so first index is returned).
What is the simplest way to get this?
As this is tagged numpy, you can use numpy.argsort on the opposite values (for reverse sorting), then slice to get the K desired values:
a = np.array([3,5,7,12,4,18,1,5,18])
K = 3
out = np.argsort(-a)[:K]
output: array([3, 2, 1])
If you want the indices in order of the original array but not necessarily sorted themselves in order of the values, you can also use numpy.argpartition:
out = np.argpartition(a, K)[-K:]
I assume you mean 3,2,1 right?
[a.index(i) for i in sorted(a)[:3:-1]]
Personally, I would create a sorted list through the sorted method, then compare the first K values with the .index attribute of a. This will yield you your desired result.
K = 3 #Number of elemens
a = [3,5,7,12,4,1,5]
a_sorted = sorted(a,reverse=True)
b = [a.index(v) for v in a_sorted[:K]]
print(b)
>>> [3, 2, 1]

Use List 2 to define the value of List 1

I am very new to Python and I can't seem to figure out how I can have two lists communicate with each other.
Here is what I am trying to achieve:
List 1 = [a, b, c]
List 2 = [1, 2, 3]
List 1 = 'b'
print(List 2)
Output: 2
I am looking for the code to evaluate the position of the item in List 1 and output the result of List 2 at the same exact position. How could I do that?
If both lists are incremented numbers, can I use the range?
Thank you in advance.
Python uses zero-based indexing. That means, the first element of List_1, a has an index 0, the second b has index 1, and so on.
If you tried accessing List_1 elements using List_2 like this List_1[List_2[0]] then you won't be able to access the first element because List_2 does not contain 0.

Sum elements of a nested list and make a new list

I want to create a new list.
The new list will be 4 elements.
X = [0, 1, 2, 3]
Each of the 4 elements will be sums from 50 lists in a bigger list.
This bigger list has 50 elements all list. Inside each of the 50 nested lists.
Each of the nestedlists have these 5 elements
Nestedlist = [str, int, int, float, float]
['Ohio', 11568495, 11568495, 262851.0, 44824.9]
In this part I've sorted through the data and changed elements 1-4 in the 50 nestedlists in to integers and floating numbers.
This is how I turned elements 1-4 into int and float:
for i, sd in enumerate(statesData):
sd = sd.strip().split(',')
if i: # omit element 0
sd[1:] = int(sd[1]), int(sd[1]), float(sd[3]), float(sd[4])
statesData[i] = sd
Now I want to find the sum of elements 1 2 3 4 of the nested lists and create a new list X (shown above):
So this is what I have:
sums = []
for e in statesData:
if e:
e = sum(e[1]), sum(e[2]), sum(e[3]), sum(e[4])
sums.append(e)
The output should look like this:
sums = [sum all nested lists element 1, sum of nested lists element 2, sum of nested lists element 3, sum of nested lists element 4]
the output I am getting is
unsupported operand type for +: int and str
How can I take a specific elements from multiple nested lists and make use of them?
If I want to use every element 2 of lists 1:50 inside list X
I feel this should be a lot easier. Even tho I am new I feel like this would be a common question. To take the same elements of multiple lists inside a larger list and play with the data.
The issue is your for loop declaration,
for e in range(len(statesData)):
If len(statesData) is 4, then e will be 0,1,2,3 during the run of the loop. However, the code treats e as a list, indexing it multiple time here:
e[1:5] = sum(e[1]), sum(e[2]), sum(e[3]), sum(e[4])
Another issue is the sum, as it needs to take a list of values, not individual ints.
It would help if I could see what statesData looks like. But, assuming that you want to get it in chunks of 4, you could do something like this...
for e in range(0, len(statesData), 4):
newVal = sum(statesData[e], statesData[e+1], statesData[e+2], statesData[e+3])
sums.append(e)
This for loop counts by 4, so e will be 0, 4, 8, etc. Then, it uses e as an index to get 4 values of statesData. So the first loop it gets 0,1,2,3 and sums them. Then it gets 4,5,6,7 and sums them, so on and so on. It then appends that summation to the sums list. I'm not sure this is exactly what you are looking for, so let me know where I went wrong. But the specific error of int is not subscriptable is coming form the fact e is declared as an int in the for loop.
You can use zip and map to apply operations in a columnwise direction:
allStates = list(map(sum,[*zip(*statesData)][1:]))

How do you find the index of an element in an Array on Python while in loop

Sorry but I'm fairly new to programming and cannot seem to find anything that relates to what I need...
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
The above code presents an output that has the index out of bounds...
Note that Array1 has less elements then Array.
I'm wondering how it would be possible to run the loop without the error and I'm not really sure what is causing the error.
Thank you!
i is an index and you are updating it too often. Move the indentation of i = i+1 to get rid of the index out of bounds.
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
If you only want the first index (or there will only be one index) then you can use the index function:
for i in array2:
if i in array1:
print array1.index(i)
To get a list of the indices:
print [array2.index(i) for i in array1 if i in array2]
You can test whether a value is in a list by using the in membership testing operator:
Array = [1,2,3,4,5,6,7,8]
Array1 = [2,9,3,9,1,9,2]
for i, value in enumerate(Array1):
if value in Array:
print i
output
0
2
4
6
It looks as if you want to print all indexes in the inner array where the value matches a value in the output array:
array1 = [1,2,3,4,5,6,7,8]
array2 = [2,9,3,9,1,9,2]
for i,a1 in enumerate(array1):
for j,a2 in enumerate(array2):
if a1 == a2:
print j
Output:
4
0
6
2
If you want to collect the indices, you a list comprehension:
print [j for i,a1 in enumerate(array1) for j,a2 in enumerate(array2) if a1 == a2]
Output:
[4, 0, 6, 2]
Or maybe in sorted order:
print sorted(j for i,a1 in enumerate(array1) for j,a2 in enumerate(array2) if a1 == a2)
Output:
[0, 2, 4, 6]
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
If I understand correctly, you are thinking that i shouldn't go above the size of Array, because you have a while i < size(Array) But the while condition only controls whether the loop will repeat, it does not guarantee that i will remain less then size throughout the loop.
You seem to be thinking that this will loop over the arrays once, but because one loop is inside the other: the loop itself will be repeated.
In this case, i is incremented inside the inner loop once for every element in Array1, which causes it to become too high for indexing Array.
I think what you want is to iterate over both lists at the same time. Don't do this by creating two loops, you only want one loop.
for index, k in enumerate(Array):
if k == Array1[index]:
print index
A better approach, but perhaps harder to understand for a beginner is this:
for index, (value1, value2) in enumerate(zip(Array, Array1)):
if value1 == value2:
print index
Zip "zips" the two lists together which makes it really easy to iterate over both in parallel.

Categories

Resources