This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 5 years ago.
I'm currently writing a function that runs through a list of elements, and only does operation on list elements that are integers. It looks like this:
for n in list1:
if n == int:
#Do stuff
What I'm struggling with is how to actually write out the loop to detect if the element is an integer. What should I do for this? I can't find anything in the docs of Python (Although maybe I haven't looked deep enough in).
Thanks for any help.
Use the isinstance() function:
for n in list1:
if isinstance(n, int):
# Do stuff
for n in list1:
if isinstance( n, ( int, long )):
#dostuff
Related
This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 3 years ago.
I am trying to find duplicates inside an array.
my array looks like:
['LM_Auto', 'LM_Auto', 'LM_Op', 'LM_Op']
and much longer with a few thousand of these pairs.
def clear_stemmed_LM(collection):
i = 0
ele = i+1
for i in collection:
for ele in collection:
if i == ele:
del collection[ele]
return collection
the error says the list indices must be integers or slices not strings. How can I compare strings in an array?
[if x+1 for in x range] #Idea
or something similar like this?
If you just need to purge the duplicates in the list collection, as it seems from the code, list(set(collection)).
This is a very, very common and basic issue. I encourage you to Google thoroughly first!
for i in collection iters over the items so in i you'll find the first string not the index. Use for i in range(len(collection)) instead
This question already has answers here:
How to declare and add items to an array in Python?
(8 answers)
Closed 5 years ago.
dist=[a,b,c,d,e]
spset=[1,3]
k=[]
for m in range(1,self.n+1):
if m not in spset:
k+=dist[m]
I'm trying to make a list k that contains the all elements of dist except the ones with whose indexes are in spset[]. What am I doing wrong? The error is:
k+=dist[m]
TypeError: 'int' object is not iterable
The problem might be the one stated by #SuperSaiyan. Also, here you have another possible solution more compact and simple:
[x for i,x in enumerate(dist) if i not in spset]
Because dist[m] is probably an int. You are trying to "Extend" a list through the += operation. You probably want k.append(dist[m]).
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I'm trying to delete binary numbers from a list that don't contain the number of zeroes a user enters.
a = []
for i in range(512):
a.append(format(i, '09b'))
b = int(input("Enter zeroes: "))
for i in a:
if i.count('0') != b:
del(i)
for i in a:
print(i)
But running this code still yields the full list of 9 bit numbers. Where am I going wrong?
You need to use a.pop in order to delete something from the list.
However, you'd be much better off simply recreating the list, like this:
new_a = [i for i in a if i.count('0') == b]
It's more functional, and more clearly expresses what you're trying to do. It's also possibly more efficient. Deleting items randomly from a list is a linear operation. If you do it n times, you might end up with a quadratic algorithm. Rebuilding the list is only linear.
This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 8 years ago.
I am using the following function in order to sort a list in an increasing order. However, while my function works for lists such as: [1,5,6,9,3] or [56,43,16,97,45], it does not work for lists of the form: [20,10,1,3,50].
In such cases, the computer seems to consider that 3>20 and 3>10 and 3 ends up right before 50 (second to last) in the "sorted" list I get. More precisely the result I get is: [1,10,20,3,50].
Here is my code:
def function_sort(L):
for j in range(len(L)):
min=j
for i in range(j+1,len(L)):
if L[i]<L[min]:
min = i
if(min != j):
L[j],L[min] = L[min],L[j]
print L
return L
Could anyone please explain me what is going on?
It sounds like your list consists of strings rather than integers, and you end up getting the elements sorted lexicographically.
By way of illustration, consider the following:
>>> 10 < 2
False
>>> '10' < '2'
True
To fix the issue, convert the elements to integers before sorting:
L = map(int, L)
P.S. I recommend against using min as a variable name since it shadows the built-in function min().
This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 8 years ago.
I am trying to compare elements of a list u for equality.
A possible solution could be all(x == u[0] for x in u[1:]), or simply all(x == u[0] for x in u), but it looks rather weird.
In Python, it's possible to write a == b == c, with its usual "mathematical" meaning. So I thought I could, with the help of the operator module, write operator.eq(*u). However, the eq function takes only two arguments. Of course, functools.reduce(operator.eq, u) is of no use here, since after the first test eq(u[0], u[1]), I get a boolean, and it will fail when doing the second test, eq(<bool>, u[2]).
Is there a better way than the solution above? A more... "pythonic" way?
len(set(u)) == 1 is pretty Pythonic.