Lets say i have a list of list containing:
[[1,'A'],[2,'B'],[3,'C']]
and i want to print it out as such:
1 A
2 B
3 C
I was thinking of using a for loop to print each element in the list of list but I wasn't quite sure of it.
lst = [[1,'A'],[2,'B'],[3,'C']]
for i in lst:
print(lst[i]) #perhaps needing to use \n in the loop?
You can unpack each nested list like this:
for num, let in lst:
print(num, let)
What you're currently doing, with for i in lst, is printing each element in lst, while you seem to think the for i in lst syntax, accompanying the lst[i] indexing, is, well, indexing the list. That's not how that works.
If you wanted your desired output while iterating in this fashion, try this:
for i in range(len(lst)):
print(' '.join(lst[i]))
More simply, you could do this:
for i in lst:
print(' '.join(i))
try this:
for i in lst:
print(i[0], i[1])
Related
I'm trying to manually make a function that removes duplicates from a list. I know there is a Python function that does something similar (set()), but I want to create my own. This is what I have:
def remove(lst):
for i in range(len(lst)):
aux = lst[0:i] + lst[i+1:len(lst)]
if lst[i] in aux:
del(lst[i])
return lst
I was trying something like creating a sub-list with all the items except the one the for is currently on, and then check if the item is still in the list. If it is, remove it.
The problem is that it gives me an index out of range error. Does the for i in range(len(lst)): line not update every time it starts over? Since I'm removing items from the list, the list will be shorter, so for a list that has 10 items and 2 duplicates, it will go up to index 9 instead of stopping on the 7th.
Is there anyway to fix this, or should I just try doing this is another way?
I know this does not fix your current script, but would something like this work?
def remove(lst):
unique=[]
for i in lst:
if i not in unique: unique.append(i)
return unique
Just simply looping through, creating another list and checking for membership?
The problem is you are manipulating the list as you are iterating over it. This means that when you reach the end of the list, it is now shorter because you're removed elements. You should (generally) avoid removing elements while you are looping over lists.
You got it the first time: len(lst) is evaluated only when you enter the loop. If you want it re-evaluated, try the while version:
i = 0
while i < len(lst):
...
i += 1
Next, you get to worry about another problem: you increment i only when you don't delete an item. When you do delete, shortening the list gets you to the next element.
i = 0
while i < len(lst):
aux = lst[0:i] + lst[i+1:len(lst)]
if lst[i] in aux:
del(lst[i])
else:
i += 1
I think that should solve your problem ... using the logic you intended.
def remove(lst):
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
return new_list
You should append the values to a secondary list. As Bobbyrogers said, it's not a good idea to iterate over a list that is changing.
You can also try this:
lst = [1,2,3,3,4,4,5,6]
lst2 = []
for i in lst:
if i not in lst2:
lst2.append(i)
print(lst2)
[1, 2, 3, 4, 5, 6]
I do not know much about python so i apologize if my question is a very basic one.
Let's say i have a list
lst = [1,2,3,4,5,6,7,8,9,10]
Now what i want to know is that if there is any way to write the following piece of code in python without using range() or xrange():
for i in lst:
for j in lst after element i: '''This is the line i want the syntax for'''
#Do Something
The second loop is to access elements after the element i i.e., if i = 3, j would have to loop through from 4 to 10, so the pairs of numbers if i and j are printed would be (1,2)..(1,10), (2,3)...(2,10), (3,4)..(3,10) etc.
I have no idea what to search for or what query to type on any search engine.
Any help would be much appreciated.
This is what list slicing is about, you can take part of your list from i'th element through
lst[i:]
furthermore, in order to have both index and value you need enumerate operation, which changes the list into list of pairs (index, value)
thus
for ind, i in enumerate(lst):
for j in lst[ind+1: ]:
#Do Something
It looks like you might want to use enumerate():
for index, item in enumerate(lst):
for j in lst[index+1:]:
#Do Something
I've got two lists of coordinates, they look like this:
list_kp2_ok:
[[1185.60009765625, 933.6000366210938], [1310.4000244140625, 828.0000610351562], [1067.0, 979.0], [1310.0, 828.0], [1423.2000732421875, 814.800048828125], [1306.0, 828.0], [3634.0, 605.0], [1308.0960693359375, 827.7120971679688], [1422.7200927734375, 815.0400390625], [1185.1199951171875, 933.1200561523438], [1186.56005859375, 923.0400390625], [1306.3681640625, 829.4401245117188], [1194.393798828125, 839.80810546875], [1187.1361083984375, 922.7520751953125], [1082.8800048828125, 849.6000366210938]]
list_kp2_2_ok:
[[835.0, 1201.0], [1086.0, 850.0], [1187.0, 924.0], [1197.0, 839.0], [1310.0, 828.0], [3634.0, 605.0], [1195.2000732421875, 838.800048828125], [1308.0, 828.0000610351562], [1084.800048828125, 849.6000366210938], [1310.4000244140625, 828.0000610351562], [1186.800048828125, 924.0000610351562], [1296.0, 956.4000244140625], [1082.8800048828125, 849.6000366210938], [1072.800048828125, 944.6400146484375], [1083.4560546875, 850.1760864257812], [1187.1361083984375, 922.7520751953125], [3633.984375, 606.528076171875], [1082.4193115234375, 850.1761474609375], [1306.3681640625, 829.4401245117188], [1181.9521484375, 966.2977294921875], [1306.3682861328125, 828.6107788085938]]
Now I need to check if there are any same coordinates on both lists and create a new list of them.
So I wrote:
list_wsp=[]
count=0
count1=0
print type(count)
print type(count1)
for count in list_kp2_ok:
for count1 in list_kp2_2_ok:
if list_kp2_ok[count]==list_kp2_2_ok[count1]:
list_wsp.append(list_kp2_ok[count])
count1=count1+1
if count1==len(list_kp2_2_ok)-1:
break
count=count+1
if count==len(list_kp2_ok)-1:
break
and...
TypeError: list indices must be integers, not list
I don't know what's wrong, couldn't find a solution...
Could anyone help me, please?
Maybe there's a simplier way to do such a thing?
Python's for loop is not indexed-based, it really iterates on the sequence (or any iterable). So in this code:
for whatever in some_iterable:
do_something_with(whatever)
whatever is successively bound to each item in some_iterable. As an example:
>>> mylist = ["A", "B", "C"]
>>> for item in mylist:
... print "item is", item
...
item is A
item is B
item is C
If you want the indexes to, you can use the builtin enumerate(iterable, start=0) function, which yields a (index, item) tuple for each item in iterable:
>>> for index, item in enumerate(mylist):
... print "item %s is %s" % (index, item)
...
item 0 is A
item 1 is B
item 2 is C
You are indexing your lists with a non-int type index:
for count in list_kp2_ok:
for count1 in list_kp2_2_ok:
if list_kp2_ok[count]==list_kp2_2_ok[count1]:
So a quick fix for that is to do it this way:
for coord1 in list_kp2_ok:
for coord2 in list_kp2_2_ok:
if coord1==coord2:
You can even do the whole coding in one statement:
list_wsp=[coords for coords in list_kp2_ok if coords in list_kp2_2_ok]
This will directly output to you the common coordinates in both lists.
You can use list comprehension:
new_list = [i for i in list_kp2_ok if i in list_kp2_2_ok]
You don't have to declare the counter variables. You can iterate through the lists with for-in:
list_wsp = []
for elem in list_k2_ok:
for elem1 in list_k2_2_ok:
if elem == elem1:
list_wsp.append(elem)
This will create the new list with the same coordinates.
An alternative approach might be to try using sets:
for x in set([tuple(l) for l in list_kp2_ok]).intersection(set([tuple(l) for l in list_kp2_2_ok])):
print x
This first converts the inner list items to tuples as they are then hashable by the set function. The answer is then the intersection of the two sets. This would remove any duplicates which may or may not be desirable.
I have a list and I am trying to delete the elements that have 'pie' in them. This is what I've done:
['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
if "pie" in list[i]:
del list[i]
I keep getting list index out of range, but when I change the del to a print statement it prints out the elements fine.
Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:
foods = ['applepie','orangepie', 'turkeycake']
pieless_foods = [f for f in foods if 'pie' not in f]
Deleting an element during iteration, changes the size, causing IndexError.
You can rewrite your code as (using List Comprehension)
L = [e for e in L if "pie" not in e]
Something like:
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]
Modifying an object that you're iterating over should be considered a no-go.
The reason to why you get a error is because you change the length of the list when you delete something!
Example:
first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).
So rather use something like:
for item in in list:
if "pie" not in item:
new list.append(item)
Another but longer way would be to note down the indexes where you encounter pie and delete those elements after the first for loop
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.
Say, I have a 2D list:
li = [[0,1,2],[3,4,5],[6,7,8]]
I would like to merge this either into one long list
li2 = [0,1,2,3,4,5,6,7,8]
or into a string with separators:
s = "0,1,2,3,4,5,6,7,8"
Really, I'd like to know how to do both.
Like so:
[ item for innerlist in outerlist for item in innerlist ]
Turning that directly into a string with separators:
','.join(str(item) for innerlist in outerlist for item in innerlist)
Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:
for innerlist in outerlist:
for item in innerlist:
...
Try that:
li=[[0,1,2],[3,4,5],[6,7,8]]
li2 = [ y for x in li for y in x]
You can read it like this:
Give me the list of every ys.
The ys come from the xs.
The xs come from li.
To map that in a string:
','.join(map(str,li2))
There's a couple choices. First, you can just create a new list and add the contents of each list to it:
li2 = []
for sublist in li:
li2.extend(sublist)
Alternately, you can use the itertools module's chain function, which produces an iterable containing all the items in multiple iterables:
import itertools
li2 = list(itertools.chain(*li))
If you take this approach, you can produce the string without creating an intermediate list:
s = ",".join(itertools.chain(*li))
My favorite, and the shortest one, is this:
li2 = sum(li, [])
and
s = ','.join(li2)
EDIT: use sum instead of reduce, (thanks Thomas Wouters!)
For the second one, there is a built-in string method to do that :
>>> print ','.join(str(x) for x in li2)
"0,1,2,3,4,5,6,7,8"
For the first one, you can use join within a comprehension list :
>>> print ",".join([",".join(str(x) for x in li])
"0,1,2,3,4,5,6,7,8"
But it's easier to use itertools.flatten :
>>> import itertools
>>> print itertools.flatten(li)
[0,1,2,3,4,5,6,7,8]
>>> print ",".join(str(x) for x in itertools.flatten(li))
"0,1,2,3,4,5,6,7,8"
N.B : itertools is a module that help you to deal with common tasks with iterators such as list, tuples or string... It's handy because it does not store a copy of the structure you're working on but process the items one by one.
EDIT : funny, I am learning plenty of way to do it. Who said that there was only one good way to do it ?
import itertools
itertools.flatten( li )
To make it a flattened list use either:
http://code.activestate.com/recipes/121294/
http://code.activestate.com/recipes/363051/
Then, join to make it a string.
Here is a way:
def convert2DArrtostring(ndArr):
'''converts 2D array to string'''
arr_str = "["
for i in ndArr:
arr_str += "["
for j in i:
arr_str += str(j) + " "
arr_str += "]\n"
arr_str += "]"
return arr_str
There are many ways to do this problem. I like Numpy's tools because it is normally already imported in everything I do. However, if you aren't using Numpy for anything else this probably isn't a good method.
import numpy
li = [[0,1,2],[3,4,5],[6,7,8]]
li2=li[0] #first element of array to merge
i=1
while i<len(li):
li2=numpy.concatenate((li2,li[i]))
i+=1
print li2
This would print [0 1 2 3 4 5 6 7 8] and then you can convert this into your string too.