Reputation: 3
All values in list B are either 1.0 or 2.
I'm trying to go through listA
(coded as "Time1) and depending on each corresponding value in listB
(Coded as Channel1) sort each term into a new list.
aka:
A = [2.3, 4.3, 3.1]
B = [1.0, 2.0, 1.0]
becomes
P = [2.3, 3.1]
Q = [4.3]
My current code for this is:
a = 0
for a in Time1:
if Channel1[a] == 1:
HistDetec1.append(Time1[a])
if Channel1[a] == 2:
HistDetec1.append(Time1[a])
a = a + 1
But this doesn't work as it think that "a" is a float
list indices must be integers, not float
Thanks for your time.
Upvotes: 0
Views: 31
Reputation: 4655
There are a few mistakes.
1 - First you are looping through the elements of A instead of indexes and try to use that elements as indexes at other list.
2 - You are appending in either case to the same list HistDetec1
3 - You try to increment index which for already do that
4 - You check equality of int values against float values
Try something like that:
for index in range(len(Time1)):
if Channel1[index] == 1.0:
HistDetec1.append(Time1[index])
elif Channel1[index] == 2.0:
HistDetec2.append(Time1[index])
Upvotes: 0
Reputation: 21694
You can just use an integer there...
B = [1, 2, 1]
Or convert to integer before checking:
if Channel1[int(a)] == 1:
Upvotes: 0
Reputation: 19851
You could use enumerate
and list comprehension:
>>> A = [2.3, 4.3, 3.1]
>>> B = [1.0, 2.0, 1.0]
>>> P = [t for i, t in enumerate(A) if B[i] == 1.0]
>>> P
[2.3, 3.1]
>>> Q = [t for i, t in enumerate(A) if B[i] == 2.0]
>>> Q
[4.3]
Or, using zip
:
>>> P = [a for a, b in zip(A, B) if b == 1.0]
>>> P
[2.3, 3.1]
>>> Q = [a for a, b in zip(A, B) if b == 2.0]
>>> Q
[4.3]
Upvotes: 1