I'm looking for a method of inserting values to 2D lists in Python. My sample list is as follows:
List= [ ['A', 'B'], ['C', 'D'] ]
I would like to insert a value at the beginning of each list within my List, so that it would look like this:
List = [ ['#','A', 'B'], ['#','C', 'D'] ]
I have written a function as follows:
def Foo(l):
rows = len(l)
cols = len(l[0])
for row in xrange(rows):
l.insert(row, '#')
But that has given me the following output:
List= [ '#', '#', ['A', 'B'], ['C', 'D'] ]
when you do l.insert() it adds an item to l not the sub lists, to iterate over the sub lists you can do:
for row in l:
row.insert(0,"#")
Or using xrange:
for i in xrange(len(l)):
l[i].insert(0,"#")
Related
Im trying to join the letters as a string that's inside the list which is also inside the list. So for example, it looks like this [['a', 'b', 'c'], ['d', 'e', 'f']] however I want the result to look like 'ad be cf' which is basically taking the element that lies in the same position in the list. I know how to join the elements into a list that can look like 'abcdef', however, i don't know which I could add in order to return a string that looks like above.
Any advice would be thankful!
string = ''
new_grid = []
for a in grid:
for b in a:
string += b
return string
When you want to transpose lists into columns, you typically reach for zip(). For example:
l = [['a', 'b', 'c'], ['d', 'e', 'f']]
# make a list of columns
substrings = ["".join(sub) for sub in zip(*l)]
#['ad', 'be', 'cf']
print(" ".join(substrings))
# alternatively print(*substrings, sep=" ")
# ad be cf
This works:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = [list(pair) for pair in zip(my_list[0], my_list[1])]
for i in range(3):
string = ''.join(sorted_list[i])
print(string, end=" ")
First, we are pairing each individual list to its corresponding value using [zip][1], then we are joining it into a string, and printing it out.
This solution may not be the most efficient, but it's simple to understand.
Another quick solution without zip could look like this:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = list(map(lambda a, b: a + b, my_list[0], my_list[1]))
print(" ".join(sorted_list))
I need to make a new list that contains alternating elements from the two list from before.
example: listA = "a","b","c"
listB= "A","B","C"
the output should be "a","A","b","B","c","C"
def one_each(lst1,lst2):
newList=[]
for i in range(len(lst2)):
newList.append(lst1[i])
newList.append(lst2[i])
return newList
you have to use small length list to reiterate so, add if condition to get your length
try this one:
def one_each(lst1,lst2):
iRange=len(lst1)
if len(lst2)<iRange:
iRange=len(lst2)
newList=[]
for i in range(iRange):
newList.append(lst1[i])
newList.append(lst2[i])
return newList
print (['a','b','c'],['A','B','C','D'])
output:
['a', 'A', 'b', 'B', 'c', 'C', 'c']
Try using a single loop over the index range of one of the two lists, then append an element from each list at each iteration.
def one_each(lst1, lst2):
lst = []
for i in range(0, len(lst1)):
lst.append(lst1[i])
lst.append(lst2[i])
return lst
lst1 = ['a', 'b', 'c']
lst2 = ['A', 'B', 'C']
output = one_each(lst1, lst2)
print(output)
This prints:
['a', 'A', 'b', 'B', 'c', 'C']
Try this
I've used zip and concate all the elements.
listA = ["a","b","c"]
listB= ["A","B","C"]
print reduce(lambda x,y:x+y,zip(listA, listB))
Result: ('a', 'A', 'b', 'B', 'c', 'C')
If I had a list like this:
L = [
['a', 'b'],
['c', 'f'],
['d', 'e']
]
I know that I could check if e.g. 'f' was contained in any of the sub lists by using any in the following way:
if any('f' in sublist for sublist in L) # True
But how would I go about searching through second sub lists, i.e. if the list was initialized the following way:
L = [
[
['a', 'b'],
['c', 'f'],
['d', 'e']
],
[
['z', 'i', 'l'],
['k']
]
]
I tried chaining the for in expressions like this:
if any('f' in second_sublist for second_sublist in sublist for sublist in L)
However, this crashes because name 'sublist' is not defined.
First write your logic as a regular for loop:
for first_sub in L:
for second_sub in first_sub:
if 'f' in second_sub:
print('Match!')
break
Then rewrite as a generator expression with the for statements in the same order:
any('f' in second_sub for first_sub in L for second_sub in first_sub)
If you don't need to know where 'f' is located you can leverage itertools here as well.
import itertools
any('f' in x for x in itertools.chain.from_iterable(l))
This will flatten your nested lists and evaluate each list separately. The benefit here is if you have three nested lists this solution would still function without having to continue writing nest for loops.
I want to extract unique data from nested list, see below. I implemented two way of this. First one works good, but second one failed. Is new_data is empty during calculation? And how do I fix it?
data = [
['a', 'b'],
['a', 'c'],
['a', 'b'],
['b', 'a']
]
# working
new_data = []
for d in data:
if d not in new_data:
new_data.append(d)
print(new_data)
# [['a', 'b'], ['a','c'], ['b','a']]
# Failed to extract unique list
new_data = []
new_data = [d for d in data if d not in new_data]
print(new_data)
# [['a', 'b'], ['a', 'c'], ['a', 'b'], ['b', 'a']]
Just try:
new_data = [list(y) for y in set([tuple(x) for x in data])]
You cannot use set() on a list of lists because lists are not hashable. You convert the list of lists into a list of tuples. Apply set() to remove the duplicates. Then convert the de duplicated list of tuples back into a list of lists.
you could use enumerate to test that there are no copies before the current value such that only the first instance of a copy is taken:
new_data = [item for index, item in enumerate(data) if item not in data[:index]]
answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = []
I want to compare index 0 in list1 to index 0 in list2 and, if they are equal, move to compare index 1 in each list.
In this instance index 1 in list1 != index 1 in list 2 so I want to append index+1 and the incorrect student answer (in this case the letter c) to the empty list. This is what I tried - unsuccessfully.
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x in list1:
for y in list2:
if x != y:
incorrect.append(y)
print(incorrect)
main()
Since you need to compare lists element-by-element, you also need to iterate over those list simultaneously. There is more than one way to do this, here are a few.
Built-in function zip allows you to iterate over multiple iterable objects. This would be my method of choice because, in my opinion, it's the easiest and the most readable way to iterate over several sequences all at once.
for x,y in zip(list1, list2):
if x != y:
incorrect.append(y)
The other way would be to use method enumerate:
for pos, value in enumerate(list1):
if value != list2[pos]:
incorrect.append(list2[pos])
Enumerate takes care of keeping track of indexing for you, so you don't need to create a special counter just for that.
The third way is to iterate over lists using index. One way to do this is to write:
for pos range(len(list1)):
if list1[pos] != list2[pos]:
incorrect.append(list2[pos])
Notice how by using enumerate you can get index out-of-the-box.
All of those methods can also be written using list comprehensions, but in my opinion, this is more readable.
You can use enumerate and list comprehension to check the index comparison.
answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = [y for x,y in enumerate(answer_list) if y != student_answers[x]]
incorrect
['b', 'c']
If you want the indexes that don't match and the values:
incorrect = [[y,answer_list.index(y)] for x,y in enumerate(answer_list) if y != student_answers[x]]
[['b', 1], ['c', 2]]
In x,y in enumerate(answer_list), the x is the index of the element and y is the element itself, so checking if y != student_answers[x] is comparing the elements at the same index in both lists. If they don't match, the element y is added to our list.
Using a loop similar to your own:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append(y)
print(incorrect)
In [20]: main()
['b', 'c']
To get element and index:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append([y,list1.index(y)])
print(incorrect)
In [2]: main()
[['b', 1], ['c', 2]]