I have a list in my program: grid = []
The grid currently holds lines of strings in a format such as:
qwertyui
asdfghjk
zxcvbnml
I want to alter the list so that its format is changed to:
zaq
xsw
cde
vfr
bgt
nhy
mju
lki
So in a sense the list would just be turned 90 degrees clockwise. I also want to store the newly formatted strings in a different list called diff_grid[].
Use zip(), and keep in mind that it'll take the first element from each item, then the second, and so on.
>>> strings = ['qwertyui', 'asdfghjk', 'zxcvbnml']
>>> for item in zip(*(strings[::-1])):
... print(item)
...
('z', 'a', 'q')
('x', 's', 'w')
('c', 'd', 'e')
('v', 'f', 'r')
('b', 'g', 't')
('n', 'h', 'y')
('m', 'j', 'u')
('l', 'k', 'i')
If you wanted ('q', 'a', 'z') instead of ('z', 'a', 'q'), you wouldn't need the [::-1] that reverses the list of strings.
If you don't want to see the tuple structure in the output, you can use join() or unpack the tuple and use a custom end argument:
>>> for item in zip(*(strings[::-1])):
... print(*item, sep='')
...
zaq
xsw
cde
vfr
bgt
nhy
mju
lki
Assuming grid is a list of the strings you are referring to:
>>> grid = ["abc", "def", "xyz"]
Try
>>> diff_grid = [''.join(i) for i in zip(*grid[::-1])]
>>> diff_grid
['xda', 'yeb', 'zfc']
zip(*grid) will apply the zip operator on the strings of grid.
Note that you have to reverse grid (grid[::-1]) because of the order the zip operation is applied.
Related
I have a list of strings
X=['kmo','catlin','mept']
I was trying to write a loop that would return a list that contains lists of every Nth letter of each word:
[['k','c','m'], ['m','a','e'],['o','t','p']]
But all the methods I tried only returned a list of all the letters returned consecutively in one list:
['k','m','o','c','a','t','l','i'.....'t']
Here is one version of my code:
def letters(X):
prefix=[]
for i in X:
j=0
while j < len(i):
while j < len(i):
prefix.append(i[j])
break
j+=1
return prefix
I know I'm looping within each word, but I'm not sure how to correct it.
It seems that the length of the resulting list is dictated by the length of the smallest string in the original list. If that is indeed the case, you could simply do it like this:
X = ['kmo','catlin','mept']
l = len(min(X, key=len))
res = [[x[i] for x in X] for i in range(l)]
which returns:
print(res) # -> [['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]
or the even simpler (kudos #JonClemens):
res = [list(el) for el in zip(*X)]
with the same result. Note that this works because zip automatically stops iterating as soon as one of its elements is depleted.
If you want to fill the blanks so to speak, itertools has got your back with its zip_longest method. See this for more information. The fillvalue can be anything you chose; here, '-' is used to demonstrate the use. An empty string '' might be a better option for production code.
res = list(zip_longest(*X, fillvalue = '-'))
print(res) # -> [('k', 'c', 'm'), ('m', 'a', 'e'), ('o', 't', 'p'), ('-', 'l', 't'), ('-', 'i', '-'), ('-', 'n', '-')]
You can use zip.
output=list(zip(*X))
print(output)
*X will unpack all the elements present in X.
After unpacking I'm zipping all of them together. The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc. Finally, I wrapped everything in a list using list.
output
[('k', 'c', 'm'), ('m', 'a', 'e'), ('o', 't', 'p')]
If you want output to be a list of lists. Then use map.
output=list(map(list,zip(*X)))
print(output)
output
[['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]
X=['kmo','catlin','mept']
y = []
j=0
for i in X:
item =''
for element in X :
if (len(element) > j):
item = item + element[j]
y.append(item)
j=j+1
print("X = [",X,"]")
print("Y = [",y,"]")
try this
def letters(X):
prefix=[]
# First lets zip the list element
zip_elemets = zip(*X)
for element in zip_elemets:
prefix.append(list(element))
return prefix
The goal was to create a list of all possible combinations of certain letters in a word... Which is fine, except it now ends up as a list of tuples with too many quotes and commas.
import itertools
mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))
outp = (list(itertools.permutations(mainword,n_word)))
What I want:
[yes, yse, eys, esy, sye, sey]
What I'm getting:
[('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')]
Looks to me I just need to remove all the brackets, quotes, and commas.
I've tried:
def remove(old_list, val):
new_list = []
for items in old_list:
if items!=val:
new_list.append(items)
return new_list
print(new_list)
where I just run the function a few times. But it doesn't work.
You can recombine those tuples with a comprehension like:
Code:
new_list = [''.join(d) for d in old_list]
Test Code:
data = [
('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'),
('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')
]
data_new = [''.join(d) for d in data]
print(data_new)
Results:
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
You need to call str.join() on your string tuples in order to convert it back to a single string. Your code can be simplified with list comprehension as:
>>> from itertools import permutations
>>> word = 'yes'
>>> [''.join(w) for w in permutations(word)]
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
OR you may also use map() to get the desired result as:
>>> list(map(''.join, permutations(word)))
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
You can use the join function . Below code works perfect .
I am also attach the screenshot of the output.
import itertools
mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))
outp = (list(itertools.permutations(mainword,n_word)))
for i in range(0,6):
outp[i]=''.join(outp[i])
print(outp)
I have data in following format:
[('A', 'B', 'C'),
('B', 'C', 'A'),
('C', 'B', 'B')]
I'm looking to get this:
ABC
BCA
CBB
I'm able to convert one tuple at the time:
>> "".join(data[0])
.. 'ABC'
However when I'm trying to conver the whole list Python gives me an error:
>> "".join(data[:])
.. TypeError: sequence item 0: expected string, tuple found
Any advice how I'll be able to convert the whole list?
Thank you!
.join expects a sequence of strings, but you're giving it a sequence of tuples.
To get the result you posted, you'll need to join each element in each tuple, and then join each tuple together:
print('\n'.join(''.join(elems) for elems in data))
This works because .join will accept a generator expression, allowing you to iterate over data (your list of tuples).
We therefore have two joins going on: the inner join builds a string of the three letters (eg, 'ABC'), and the outer join places newline characters ('\n') between them.
lst=[('A', 'B', 'C'),
('B', 'C', 'A'),
('C', 'B', 'B')]
for x in lst:
print ("".join(x))
Output is;
>>>
ABC
BCA
CBB
>>>
One-liner;
print ("\n".join(["".join(x) for x in lst]))
You have to reach each element in the list first.
a = [('A', 'B', 'C'), ('B', 'C', 'A'), ('C', 'B', 'B')]
print ["".join(line) for line in a]
I want to find combinations of elements in a string. baseString is of variable length e.g. 'tbyhn' or 'tg' or so on.
I tried:
import itertools
baseString = 'tgby'
prd = [it for it in itertools.product(base,repeat=len(baseString)-1)]
prd is a list that looks like this:
[('t', 't', 't'), ('t', 't', 'g'), ('t', 't', 'b'), ..., ('y', 'y', 'y')]
I would like the list to look like this:
['ttt','ttg','ttb','tty','tgt',...,'yyy']
How can I do that?
Also, if I ever have a list of tuples like 'prd' how do I chain only the elements that are in each tuple.
EDIT
I didn't want these types of outcomes:
x = ['t','t','t','t','t','g','t','t','b','t','t','y',...,'y','y','y']
x = ['tttttgttbttytgt...yyy']
Simply join them like this
bS = 'tgby'
prd = ["".join(it) for it in itertools.product(bS, repeat=len(bS)-1)]
Edit: A faster version, suggested by #alko in the comments
prd = map(''.join, itertools.product(bS, repeat=len(bS)-1))
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
I have a list
['r', 'o', 'c', 'o', 'c', 'o']`
and wish to make it
[['r','o'], ['c', 'o'], ['c', 'o']]
how would I do this?
moreover, I need to make the new list grouped to whatever "n" is
in the above example, n is 2
if n is 3, the result should be:
[['r', 'o', 'c']['o','c','o']]
The itertools recipes have a general-purpose function that does exactly what you're looking for with any kind of iterator, called grouper:
>>> values = ['r', 'o', 'c', 'o', 'c', 'o']
>>> groups = grouper(values, 3)
However, this returns you an iterator. If you want a list, you have to ask for one explicitly:
>>> groups = list(grouper(values, 3))
>>> print(groups)
[('r', 'o', 'c'), ('o', 'c', 'o')]
Also, note that this gives you a list of tuples, not a list of lists. Most likely this doesn't actually matter to you. But if it does, you'll have to convert them:
>>> list_groups = [list(group) for group in grouper(values, 3)]
>>> print(list_groups)
[['r', 'o', 'c'], ['o', 'c', 'o']]
If you install more_itertools off PyPI, you can just from more_itertools import grouper. Otherwise, you'll have to copy and paste from the recipes into your code.
But either way, it's worth understanding how grouper works:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
First, it creates an iterator out of your iterable. (This is something that keeps track of its current position and returns values one by one as you call next on it, until you've reached the end.) Then it makes n references to that iterator. This is the tricky bit—you don't want n separate iterators to the same list, you want n references to the same iterator, so if you grab the next value out of the first iterator, they all move forward. That's why it does the funny [iter(iterable)] * n bit. Then it just zips the iterators together. So, the first pass through the zip calls next on the first iterator, then the second, then the third; the second pass through the zip again calls next on the first iterator, then the second, then the third; and so on.
The reason it uses zip_longest instead of just zip (or, in Python 2.x, izip_longest vs. izip) is so list(grouper(['r', 'o', 'c', 'o'], 3)) will give you [('r', 'o', 'c'), ('o', None, None)] instead of just [('r', 'o', 'c')]. If that's not what you want, it's trivial to just use the other function instead.
For further explanation, see this blog post.
Something like this?
>>> a = ['r', 'o', 'c', 'o', 'c', 'o']
>>> zip(*[iter(a)]*2)
[('r', 'o'), ('c', 'o'), ('c', 'o')]
>>> zip(*[iter(a)]*3)
[('r', 'o', 'c'), ('o', 'c', 'o')]
You can change the 2 and 3 to the number you want.
[l[i:i+n] for i in range(0, len(l), n)]