Reputation: 43
I am trying to compare a variable to the values that are stored in an array. The values in the array are extracted out from a csv file. If the values of the array are equal to the variable it will print out true.
import csv
array=[]
values = csv.reader(open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r'),
delimiter=',',
quotechar='|')
for row in values:
array.append(row[5])
number= 4200
for a in array:
if number == a:
print ('True')
print ('False')
The code only compares one value in the array and returns a false. How do I compare all the values in the array to the variable?
Upvotes: 1
Views: 16624
Reputation: 2056
Because it is exiting from the loop after it hits the first true value. Use the following code:
for i in array:
if number == i:
print ('True')
else:
print ('False')
Upvotes: 0
Reputation: 17552
From what I could figure out from your comment, this is probably what you are looking for:
array=[]
with open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r') as file:
lines = [line.split() for line in file.readlines()]
for line in lines:
try:
array.append(float(line[5]))
except ValueError:
pass
number= 4200
for a in array:
if number == a:
print ('True')
print ('Done, all checked')
Upvotes: 0
Reputation: 7268
You can use all()
- builtin function
all (number == a for a in array)
Upvotes: 0
Reputation: 37509
Use the all
function with list comprehensions
number = 10
array = [1, 2, 3, 4]
print( all(number == a for a in array) )
# False
array = [10, 10, 10, 10]
print( all(number == a for a in array) )
# True
Upvotes: 3