For loop inside another for loop Python - python

How do you add one list to another, I keep running into the problem of the second list in my for loop going through the whole list.
If aList was [1, 2, 3, 4], I want the output be 1hello, 2good, 3what... so on.
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for n in myList:
newList.append[element+n]
Input:
[1, 2, 3, 4]
Expected output:
['1hello', '2good', '3what', '4tree']

You want zip:
def function(aList):
myList = ['hello', 'good', 'what', 'tree']
return [str(a) + b for a, b in zip(aList, myList)]
Output:
In [4]: function([1, 2, 3, 4])
Out[4]: ['1hello', '2good', '3what', '4tree']
You also need to cast the passed in value to a string to make sure you can concatenate to the strings in your myList.

Read about List Comprehensions
aList = ['1', '2', '3']
print [element + n for element in aList for n in myList]
['1hello', '1good', '1what', '1tree', '2hello', '2good', '2what', '2tree', '3hello', '3good', '3what', '3tree']
or zip
aList = ['1', '2', '3']
print [element + n for element, n in zip(aList, myList)]
['1hello', '2good', '3what']

In Your question I feel no need to add two for loop. One loop itself sufficient.
let me give two cases, which one will match your need use that.
Case 1: - with one for loop
aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for i in range(len(aList)):
newList.append(str(aList[i]) + myList [i] )
return newList
this will return 1hello , 2good ...
Case 2: - with two for loop
aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for i in range(len(myList )):
newList.append(str(element) + myList [i] )
return newList
this will return 1hello , 1good ... 2hello, 2good
I hope this will help...

Related

How to remove item in list in list with list comprehension

I have a large list like this:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
I'm trying to remove all numbers within the lists of this list. So I made a list of numbers as strings from 1 to 100:
def integers(a, b):
return list(range(a, b+1))
numb = integers(1,100)
numbs = []
for i in range(len(numb)):
numbs.append(str(numb[i])) # strings
numbs = ['1','2',....'100']
How can I iterate through lists in mylist and remove the numbers in numbs? Can I use list comprehension in this case?
If number is always in the end in sublist
mylist = [ x[:-1] for x in mylist ]
mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick.
However, this isn't quite what you've asked. Nothing was actually removed from mylist, we've just built an entirely new list and reassigned it to mylist. Same logical result, though.
If numbers are always at the end and only once, you can remove the last item like:
my_new_list = [x[:-1] for x in mylist]
If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]
I would also recommend to generate the list of interger as follow :
integer_list = list(map(str, range(1, 100)))
I hope it helps :)
Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]
If you have the following list:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]
Using list comprehension to remove element in numbs
[[l for l in ls if l not in numbs] for ls in mylist]
This is a more general way to remove digit elements in a list
[[l for l in ls if not l.isdigit()] for ls in mylist]

python numpy parse array to get items

Hi I tried taking distinct items of every sublist and making an array
My input is a 2D list
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
And output I want is an array of distinct items
out = [1,2,3,5,15,657]
I tried
from numpy import np
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
anarray = np.array(alist)
newarray = []
for i in anarray:
for j in i:
if j in newarray:
pass
else:
print j
You could make use of a set:
out = set()
for inner in alist:
out.update(inner)
out = map(int, out) # in your example you have a list of ints
>>> print out
[1, 2, 3, 5, 15, 657]
from itertools import chain
alist = [['1', '2'], ['3', '5', '2'], ['15', '1'], ['5', '657', '3', '1']]
# Flatten the list into a single-level list of all the values
flattened_list = list(chain.from_iterable(alist))
# Use a set to remove the duplicates
uniques = set(flattened_list)
# Sort the unique values by the numeric value of each value
sorted_results = sorted(uniques, key=lambda value: int(value))
print sorted_results
Modifying your code slightly you can store your result in newarray:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j in newarray:
pass
else:
newarray.append(j)
Your result will be stored in newarray
To make it slightly better:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j not in newarray:
newarray.append(j)

filter lists of lists by taking out items less than a certain length - more pythonic way?

I was reading this, but I'm not sure how to do the same for looking at the length of individual items in a list. I have the following bulky code below, and I was wondering if there's a more pythonic way to do this?
indexdf = [['1','','1',], ['1', '']]
listy = []
for ilist in indexdf:
listx = [ ]
#print ilist
for x in ilist:
#print x
if len(x) > 0:
listx.append(x)
listy.append(listx)
output
listy = [['1','1']. ['1']]
listy = [ [x for x in ilist if len(x) > 0] for ilist in indexdf]
There's a further trick since the "certain length" in your example happens to exclude precisely the empty strings:
[x for x in ilist if len(x) > 0]
could be replaced with
list(filter(None, ilist))
in Python 3 or just
filter(None, ilist)
in Python 2, or
[x for x in ilist if x]
in either of them.
You can use a nested list comprehension here. Note that empty strings will return False in a boolean context. The same is true for empty lists, tuples, etc.
>>> lst = [['1','','1',], ['1', '']]
>>> lst = [[x for x in sl if x] for sl in lst]
>>> lst
[['1', '1'], ['1']]

'List of lists' to 'list' without losing empty lists from the original list of lists

Usually I would use a comprehension to change my list of lists to a list. However, I don't want to lose the empty lists as I will zip the final list to another list and I need to maintain the placings.
I have something like
list_of_lists = [['a'],['b'],[],['c'],[],[],['d']] and I use this
[x for sublist in list_of_lists for x in sublist]
which gives me
['a','b','c','d']
but what I would like is
['a','b','','c','','','d']
Sorry if this is a stupid question, I am new to python.
Thanks for any help!
Are you starting with the strings 'a', 'b', etc.? If so then you can use ''.join to convert ['a'] into 'a' and [] into ''.
[''.join(l) for l in list_of_lists]
Simply choose [''] instead of the empty list when presented with an empty sublist:
list_of_lists = [['a'],['b'], [], ['c'], [], [], ['d']]
[x for sublist in list_of_lists for x in sublist or ['']]
If you have some more complicated criteria for treating some sublists specially, you can use ... if ... else ...:
[x for sublist in list_of_lists for x in (sublist if len(sublist)%2==1 else [42])]
P.s. I'm assumig that the lack of quotes in the original is an oversight.
Something like:
a = b = c = d = 3
lol = [[a],[b],[],[c],[],[],[d]]
from itertools import chain
print list(chain.from_iterable(el or [[]] for el in lol))
# [3, 3, [], 3, [], [], 3]
>>> result = []
>>> for l in list_of_lists:
if len(l) >0:
result += l
else:
result.append('')
>>> result
['a', 'b', '', 'c', '', '', 'd']

Nested lists python

Can anyone tell me how can I call for indexes in a nested list?
Generally I just write:
for i in range (list)
but what if I have a list with nested lists as below:
Nlist = [[2,2,2],[3,3,3],[4,4,4]...]
and I want to go through the indexes of each one separately?
If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
for index2 in xrange(len(l[index1])):
print index1, index2, l[index1][index2]
But it is more pythonic to iterate through the list itself:
for inner_l in l:
for item in inner_l:
print item
If you really need the indices you can also use enumerate:
for index1, inner_l in enumerate(l):
for index2, item in enumerate(inner_l):
print index1, index2, item, l[index1][index2]
Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]
To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.
You can do this. Adapt it to your situation:
for l in Nlist:
for item in l:
print item
The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
Example:
input -> [1,2,[3,4]]
output -> [1,2,3,4]
The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
if l is not None:
e = l[0]
if isinstance(e, list):
get_elements_from_nested_list(e, new_l)
else:
new_l.append(e)
if len(l) > 1:
return get_elements_from_nested_list(l[1:], new_l)
else:
return new_l
Call of the method
l = [1,2,[3,4]]
new_l = []
get_elements_from_nested_list(l, new_l)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for numbers2 in numbers:
results.append(numbers2)
return results
print flatten(n)
Output: n = [1,2,3,4,5,6,7,8,9]
I think you want to access list values and their indices simultaneously and separately:
l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
for j in range(l_item_len):
print(f'List[{i}][{j}] : {l[i][j]}' )

Categories

Resources