Allocate each five elements of an array to a block [duplicate] - python

This question already has answers here:
How to iterate over a list in chunks
(39 answers)
Closed 5 years ago.
I have 15 elements in an array and I want to allocate each five of them to a block respectively. The elements are:
elements=["a",'b','c','d','e','f','g','h','i','j','k','l','m','n','o']
I wanted to say first 5 elements are belonged to block#1, second five are belonged to block#2 and so on. I need to do it in a loop structure as later on, I need to use the information of each block for a special task. As I am new to python I don't know how to write it. Any advice will be highly appreciated.

You can simply use list comprehension for that:
result = [elements[i:i+5] for i in range(0,len(elements),5)]
which will generate:
>>> result
[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o']]
Or more generic:
def blockify(elements,n=5):
return [elements[i:i+n] for i in range(0,len(elements),n)]
and then call it with blockify(elements,5).
What we do is we create a range that ranges from 0 to the len(elements) (length of the elements), and makes hops of 5 (or n in the generic case). Now for each of these steps, we add a slice elements[i:i+5] to the result.

Loop through all and divide index by 5 (floor division operator //)
The result of dividing is number of group.

Related

Count the number of times a sublist is in a list, no matter the order

I am sure this questions is already here, but I cannot find the answer. Basically, I need to find the number of times a set of three strings is in a list, let´s say we have:
list=['a','b','b','c', 'a', 'c', 'd']
In this case, we have two triplets of a,b,c strings. It can be found like this:
all(x in list for x in ['a', 'b', 'c']) --> True
But how can I count the number of times this triplet appears in the list, which in the list example would be 2?
Count all of the letters individually, and take the min to handle cases where you have more of some letters than others (the min is the number of complete triplets, whereas the max would include incomplete triplets).
>>> my_list = list=['a','b','b','c', 'a', 'c', 'd']
>>> min(my_list.count(x) for x in ['a', 'b', 'c'])
2

using indexes in the right way for python insert method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a bit of a problem understanding what is going on inside of an insert method in python. I have been trying to manually insert elements into an empty array, some of them are working just fine but the other ones (index 2 and index 3) ara swapped. So here in this picture I believe 'q' should be in the index of 2 and 'd' in the index of '3' but it is the other way around. I understand that when I assign 'd' on index 3, there is not enough elements in blist array to insert on 3rd index.
blist = []
blist.insert(1, "h")
blist.insert(3, "d")
blist.insert(2, "q")
blist.insert(0, "g")
blist.insert(4, "k")
intended output: ['g', 'h', 'q', 'd', 'k']
output: ['g', 'h', 'd', 'q', 'k']
if someone could help me understand what I might be doing wrong, it would be much appreciated.
If the index you are inserting in is higher than the length of the list, the string will be inserted at the end of the list.
That means if you run:
blist = []
blist.insert(1, "h")
blist.insert(3, "d")
the list will look like this:
["h","d"]
if you now run: blist.insert(2, "q") it will put q at index 2 (the end of the list)
The code is working completely fine.
Below is the explanation of what is happening at each step.
At this point there is one element in the list.
blist.insert(1, "h")
['h']
The index of h -> 0
blist.insert(3, "d")
['h', 'd']
At this point d is inserted at index 3 but as there is only one element in the list its index in the list is d -> 1
blist.insert(2, "q")
['h', 'd', 'q']
A similar thing happens for 2 as well, it is inserted at index 2 and its index in the list becomes q -> 2
Same thing is happening on further insertions
blist.insert(0, "g")
['g', 'h', 'd', 'q']
blist.insert(4, "k")
['g', 'h', 'd', 'q', 'k']
If you specifically want an array. Arrays need to first be imported, or declared, from other libraries (i.e. numpy).
if the index at which you want to insert the item does not exist it will be inserted at another position.
i recommend running code in this environment, so you can see what happens at each step, and where the items get inserted:
http://pythontutor.com/visualize.html#mode=edit
A list of the different list methods can be found:
https://www.w3schools.com/python/python_ref_list.asp

How to create a new sublist from a list whose length depends on another list [duplicate]

This question already has answers here:
Splitting a string by list of indices
(4 answers)
Closed 4 years ago.
I would like to create a new list with sub-lists inside whose length depends on another list, for example I have:
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
and I would like to have a nested list of the form:
[['a'],
['b', 'c', 'd'],
['e', 'f'],
['g', 'h', 'i', 'l', 'm'],
['n', 'o', 'p', 'q']]
Steps to solve this:
create an empty list
create a int done=0 that tells you how many things you already sliced from your data
loop over all elements of your "how to cut the other list in parts"-list
slice from done to done + whatever the current element of your "how to cut the other list in parts" is and append it to the empty list
increment done by whatever you just sliced
add the (if needed) remainder of your data
print it.
Doku:
Understanding Python's slice notation
How to "properly" print a list?
and infos about looping here: looping techniques PyTut
You can read about why we do not solve your homework for you here: open letter to students with homework problems
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
out=[]
for number in a:
out.append(b[:number])
b=b[number:]
print(out)
#[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'l', 'm'], ['n', 'o', 'p', 'q']]
Description
The out is the final output list. The loop iterates through each element in list a (say 'number') and appends a list of that many elements from the start of list b to our output list. Then it proceeds to update list b so that those elements are removed.

Printing elements of a set in python [duplicate]

This question already has answers here:
Converting a list to a set changes element order
(16 answers)
Closed 4 years ago.
I want to print the elements of the set consecutively, so I wrote the following code:
s='dmfgd'
print(set(s))
However, this code shows the output as:
set(['m', 'd', 'g', 'f'])
but, I want output like:
set(['d','m','f','g'])
Any help will be appreciated.
Set is unordered. You can instead use a list of dict keys to emulate an ordered set if you're using Python 3.6+:
print(list(dict.fromkeys(s)))
This outputs:
['d', 'm', 'f', 'g']
Python set is unordered collections of unique elements
Try:
s='dmfgd'
def removeDups(s):
res = []
for i in s:
if i not in res:
res.append(i)
return res
print(removeDups(s))
Output:
['d', 'm', 'f', 'g']

How to combine every element of a list to the other list? [duplicate]

This question already has answers here:
Element-wise addition of 2 lists?
(17 answers)
Closed 5 years ago.
Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
How can I get this without recursion or list comprehension? I mean only use loops, using python?
The itertools module implements a lot of loop-like things:
combined = []
for pair in itertools.product(['a', 'b', 'c'], ['d', 'e', 'f']):
combined.append(''.join(pair))
While iterating through the elements in the first array, you should iterate all of the elements in the second array and push the combined result into the new list.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
for j in second_list:
combined_list.append(i + j)
print(combined_list)
This concept is called a Cartesian product, and the stdlib itertools.product will build one for you - the only problem is it will give you tuples like ('a', 'd') instead of strings, but you can just pass them through join for the result you want:
from itertools import product
print(*map(''.join, product (['a','b,'c'],['d','e','f']))

Categories