How do you rotate an array of strings in Python? - python

In Python, given the following array of strings,
[ 'abc',
'def',
'ghi',
'jkl'
]
how do you transform it so it becomes,
[ 'jgda',
'kheb',
'lifc'
]

Using zip and str.join
Ex:
a = ['abc', 'def', 'ghi', 'jkl']
for i in zip(*a):
print("".join(i)[::-1])
Output:
jgda
kheb
lifc
[::-1] to reverse the string.

You could use numpy
import numpy as np
x = ['abc',
'def',
'ghi',
'jkl'
]
a = np.rot90([list(row) for row in x], 3)
result = [''.join(row) for row in a]
output:
[
'jgda',
'kheb',
'lifc'
]

Related

Add list items of one list to another list of list at same index

How can I achieve the below result? Both the list have same index size.
list_1 = [ 'arn1', 'arn2' ]
list_2 =[
['abc', '123'],
['pqr' , '789']
]
expected_output = [
['abc', '123', 'arn1'],
['pqr' , '789', 'arn2']
]
When trying to combine two lists item by item, zip is something you should always start with.
zip(list_1, list_2)
In this case, what you want is:
[ys + [x] for x, ys in zip(list_1, list_2)]
Which gives:
[['abc', '123', 'arn1'], ['pqr', '789', 'arn2']]
You can just use enumerate to loop to the first list, get the index then append to the second list.
list_1 = [ 'arn1', 'arn2' ]
list_2 =[
['abc', '123'],
['pqr' , '789']
]
for i, item in enumerate(list_1):
list_2[i].append(item)
print(list_2)
A slightly longer solution, but simpler:
list_1 = ['arn1', 'arn2']
list_2 = [['abc', '123'], ['pqr', '789']]
expected_output = [['abc', '123', 'arn1'], ['pqr', '789', 'arn2']]
output = []
for i in range(0, len(list_1)): # iterates
added_list = list_2[i] + [list_1[i]]
output.append(added_list)
print(output == expected_output)
# True
Or a list comprehension, if you want one:
output_list_comprehension = [list_2[i] + [list_1[i]] for i in range(0, len(list_1))]
#returns same answer

Is there a way to make a nested loop with as many loops as you like (python)? [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 3 years ago.
The thing i'm trying to do is to create every single combination, but only using one of each letter
I did it with 3 sets of letters
inlist = ["Aa", "Bb", "Cc"]
outlist = []
for i in inlist[0]:
for j in inlist[1]:
for k in inlist[2]:
outlist.append(str(i + j + k))
Output:
outlist = ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
What if i want to do this with 2 or 4 sets of letters? Is there an easier way?
itertools.product does exactly that:
from itertools import product
inlist = ["Aa", "Bb", "Cc"]
outlist = []
for abc in product(*inlist):
outlist.append(''.join(abc))
print(outlist)
# ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
abc is a tuple going from ('A', 'B', 'C') to ('a', 'b', 'c'). the only thing left to to is join that back to a string with ''.join(abc).
>>> import itertools
>>> inlist = ["Aa", "Bb", "Cc"]
>>> [''.join(i) for i in itertools.product(*inlist)]
['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']

Deleting data from dictionary based on starting letter

I have a data set with 4 columns, I have already opened, read, and made each column into a key/dictionary, I am trying to filter out any data which begins with a certain letter, e.g. for key DA, any value in this key with a certain starting letter (e.g. E) will result in the row being deleted. How can I go about doing this?
You can use the startswith function to check if a string starts with a certain letter. So in your case, it can be something like the following:
list_dictionary = [
{'KeyYa': 'abc', 'KeyDa': 'def', 'KeyBa': 'ghi', 'KeySa': 'jkl'},
{'KeyYa': 'abc', 'KeyDa': 'Edef', 'KeyBa': 'ghi', 'KeySa': 'jkl'},
{'KeyYa': 'abc', 'KeyDa': 'Gdef', 'KeyBa': 'ghi', 'KeySa': 'jkl'},
{'KeyYa': 'abc', 'KeyDa': 'Edef', 'KeyBa': 'ghi', 'KeySa': 'jkl'}
]
filtered = []
for line_dict in list_dictionary:
if not line_dict['KeyDa'].startswith('E'):
filtered.append(line_dict)
print(filtered)
This prints:
[{'KeyDa': 'def', 'KeyYa': 'abc', 'KeyBa': 'ghi', 'KeySa': 'jkl'}, {'KeyDa': 'Gdef', 'KeyYa': 'abc', 'KeyBa': 'ghi', 'KeySa': 'jkl'}]
If you're comfortable with the filter function and lambda, you can also do this concisely like this:
filtered = list(filter(lambda line: not line['KeyDa'].startswith('E'), list_dictionary))

Extract text from parenthesis

How can I extract the text enclosed within the parenthesis from the following string:
string = '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}'
Expected Output is:
['abc','def','ghi','jkl','mno','pqr','stu','vwx']
Regex should help.
import re
string = '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}'
res = []
for i in re.findall("\[(.*?)\]", string):
res.extend(i.replace(",", "").split())
print res
Output:
['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
An alternative using the newer regex module could be:
(?:\G(?!\A)|\[)([^][,]+)(?:,\s*)?
Broken down, this says:
(?:\G(?!\A)|\[) # match either [ or at the end of the last match
([^][,]+) # capture anything not [ or ] or ,
(?:,\s*)? # followed by , and whitespaces, eventually
See a demo on regex101.com.
In Python:
import regex as re
string = '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}'
rx = re.compile(r'(?:\G(?!\A)|\[)([^][,]+)(?:,\s*)?')
output = rx.findall(string)
print(output)
# ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']

List comprehension: Multiply each string to a single list

I have a list of strings and want to get a new list consisting on each element a number of times.
lst = ['abc', '123']
n = 3
I can do that with a for loop:
res = []
for i in lst:
res = res + [i]*n
print( res )
['abc', 'abc', 'abc', '123', '123', '123']
How do I do it with list comprehension?
My best try so far:
[ [i]*n for i in ['abc', '123'] ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]
Use a nested list comprehension
>>> lst = ['abc', '123']
>>> n = 3
>>> [i for i in lst for j in range(n)]
['abc', 'abc', 'abc', '123', '123', '123']
The idea behind this is, you loop through the list twice and you print each of the element thrice.
See What does "list comprehension" mean? How does it work and how can I use it?
It can also be done as:
>>> lst = ['abc', '123']
>>> n=3
>>> [j for i in lst for j in (i,)*n]
['abc', 'abc', 'abc', '123', '123', '123']

Categories

Resources