List item extraction in Python - python-3.x

If I have list = [1, [a,b]], how can I make split the list item in list to become list = [1, a], [1,b]?

You can first create a list then another.
then run nested for loops to individually print out each component of list2 + each component of list 1.
I spent a lot of time in this, so hope this has helped you out:
list1 = ["a", "b"]
list2 = [1, list1]
for i in list2[:-1]:
for j in list1:
print(str(i) + str(j))
If it helped, I would wish to get an 'accepted' mark!

Related

Modulo 10^9 +7 python

I have a list let's say : [1,3,5,6....,n] to very large number, that I need to report each number in the list in a new list but in "modulo 10^9+7" format in python.
How do I do it please?
I tried to search for it and people answer it's (n%m=p) and the solution is p, but I guess that's not it.
Some ways to do it. The first method is called list comprehension, and you can find many examples of it on stack overflow and elsewhere.
list1 = [1, 3, 5, 6, 201, 99121, 191929912, 8129391828989123]
modulus = 10**9 + 7
list2 = [x % modulus for x in list1] # example of list comprehension
or using map
list2 = list(map(lambda x: x % modulus, list1))
or perhaps the least elegant
list2 = []
for x in list1:
list2.append(x % modulus)

How to delete certain element(s) from an array?

I have a 2d array, how can I delete certain element(s) from it?
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
del x[i][j]
This will destroy the array and returns error "list index out of range".
you can use pop on the list item. For example -
>>> array = [[1,2,3,4], [6,7,8,9]]
>>> array [1].pop(3)
>>> array
[[1, 2, 3, 4], [6, 7, 8]]
I think this can solve your problem.
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if j<len(x[i]):
if x[i][j] == 2:
del x[i][j]
I have tested it locally and working as expected.Hope it will help.
Mutating a list while iterating over it is always a bad idea. Just make a new list and add everything except those items you want to exclude. Such as:
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
new_array = []
temp = []
delete_val = 2
for list_ in x:
for element in list_:
if element != delete_val:
temp.append(element)
new_array.append(temp)
temp = []
x = new_array
print(x)
Edit: made it a little more pythonic by omitting list indices.
I think this is more readable at the cost of temporarily more memory usage (making a new list) compared to the solution that Sai prateek has offered.

Compare unique string values between two lists and get the count of matched values in python

I have two lists with some items in common and some not. I would like to compare the two lists and get the count of items that matched.
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
Pls advice how to do this in python
Use Counters and dictionary comprehension.
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
c1 = Counter(list1)
c2 = Counter(list2)
matching = {k: c1[k]+c2[k] for k in c1.keys() if k in c2}
print(matching)
print('{} items were in both lists'.format(len(macthing))
Output:
{'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2, 'kiwi': 2}
5 items were in both lists
I think you can use set.intersection within a comprehension like this example:
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
result = {elm: list1.count(elm) + list2.count(elm) for elm in set.intersection(set(list1), set(list2))}
Output:
{'kiwi': 2, 'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2}

I want to check the occurrence of a particular item in all other items (even be it a sub string)

I want to check the occurrence of a particular item in all other items (even be it a sub string) .
n_a = ['28', '4663', '66', '66']
occ_arr = [[0,0]]*len(n_a)
for i in range(len(n_a)):
count=0
for j in range(len(n_a)):
if n_a[i] in n_a[j]:
count+=1
occ_arr[i][0] = n_a[i]
occ_arr[i][1] = count
print(occ_arr)
This is my piece of code.
The result is
[['66', 3], ['66', 3], ['66', 3], ['66', 3]]
but the desired output is
[['28', 1], ['4663', 1], ['66', 3], ['66',3]].
Please help me to figure out what is wrong with the code.
All your sub-lists in the occ_arr list are referencing the same list because you're using the * operator to copy the reference of the same list, so any change in one sub-list is reflected on all the other sub-lists. You should instead use list comprehension to create a distinct sub-lists.
Change:
occ_arr = [[0,0]]*len(n_a)
to:
occ_arr = [[0,0] for _ in range(len(n_a))]
Changing:
occ_arr = [[0,0]]*len(n_a)
To:
occ_arr = []
for i in range(len(n_a)):
occ_arr.append([0,0])
Will fix the bug occuring with the program. If you want to make this a one line statement, use the following list comprehension:
occ_arr = [[0,0] for _ in n_a]
#Add the list [0,0] for each item in the list n_a
All together, the program turns into (using the one line solution):
n_a = ['28', '4663', '66', '66']
occ_arr = [[0,0] for _ in n_a]
for i in range(len(n_a)):
count=0
for j in range(len(n_a)):
if n_a[i] in n_a[j]:
count+=1
occ_arr[i][0] = n_a[i]
occ_arr[i][1] = count
print(occ_arr)
print(occ_arr)
Explanation of bug
The reason why the bug occurs is because of the way lists are stored. Rather than being stored as literal data (like ints, floats, etc...), they are stored as objects, with memory addresses and ids. The line:
cc_arr = [[0,0]]*len(n_a)
Creates a list with it's own unique id and then copies it (shallowly [copying just the memory address, rather than the data]) four times. This can be shown through the following example:
>>> x = [[0,0]] * 4
>>> for item in x:
... print(id(x))
4500701640
4500701640
4500701640
4500701640
Note that the output will be different for you.
Hence, when you change one list, you change the underlying representation of the object, which changes the other shallow copies, which is why your program was outputting [['66', 3], ['66', 3], ['66', 3], ['66', 3]] rather than [['28', 1], ['4663', 1], ['66', 3], ['66',3]]

Python: How to find the average on each array in the list?

Lets say I have a list with three arrays as following:
[(1,2,0),(2,9,6),(2,3,6)]
Is it possible I get the average by diving each "slot" of the arrays in the list.
For example:
(1+2+2)/3, (2+0+9)/3, (0+6+6)/3
and make it become new arraylist with only 3 integers.
You can use zip to associate all of the elements in each of the interior tuples by index
tups = [(1,2,0),(2,9,6),(2,3,6)]
print([sum(x)/len(x) for x in zip(*tups)])
# [1.6666666666666667, 4.666666666666667, 4.0]
You can also do something like sum(x)//len(x) or round(sum(x)/len(x)) inside the list comprehension to get an integer.
Here are couple of ways you can do it.
data = [(1,2,0),(2,9,6),(2,3,6)]
avg_array = []
for tu in data:
avg_array.append(sum(tu)/len(tu))
print(avg_array)
using list comprehension
data = [(1,2,0),(2,9,6),(2,3,6)]
comp = [ sum(i)/len(i) for i in data]
print(comp)
Can be achieved by doing something like this.
Create an empty array. Loop through your current array and use the sum and len functions to calculate averages. Then append the average to your new array.
array = [(1,2,0),(2,9,6),(2,3,6)]
arraynew = []
for i in range(0,len(array)):
arraynew.append(sum(array[i]) / len(array[i]))
print arraynew
As you were told in the comments with sum and len it's pretty easy.
But in python I would do something like this, assuming you want to maintain decimal precision:
list = [(1, 2, 0), (2, 9, 6), (2, 3, 6)]
res = map(lambda l: round(float(sum(l)) / len(l), 2), list)
Output:
[1.0, 5.67, 3.67]
But as you said you wanted 3 ints in your question, would be like this:
res = map(lambda l: sum(l) / len(l), list)
Output:
[1, 5, 3]
Edit:
To sum the same index of each tuple, the most elegant method is the solution provided by #PatrickHaugh.
On the other hand, if you are not fond of list comprehensions and some built in functions as zip is, here's a little longer and less elegant version using a for loop:
arr = []
for i in range(0, len(list)):
arr.append(sum(l[i] for l in list) / len(list))
print(arr)
Output:
[1, 4, 4]

Resources