Python nice print - python

I have a string like this:
G O S J A J E K R A L J
I would like to print it like this:
['G', 'O', 'S', 'J', 'A'....
I tried with:
print s,
print list(s),
Any ideas ?

try
>>> l = "G O S J A J E K R A L J"
>>> l.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']
>>> ''.join(l.split())
'GOSJAJEKRALJ'

It seems that you are trying to split a string given the string and the delimiter that you wish to split on; in this case the space character. Python provides functionality to do this using the split method. A couple examples are as follows:
>>> s = "A B C D E"
>>> t = "A:B:C:D:E"
>>> s.split(" ")
['A', 'B', 'C', 'D', 'E']
>>> t.split(":")
['A', 'B', 'C', 'D', 'E']

I think you are trying to split the string -
>>> s = "G O S J A J E K R A L J"
>>> s.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']

My answer would be the same: use split for that.
But another solution (for the fun) is [x for x in l if x != ' ']
>>> l = "G O S J A J E K R A L J"
>>> [x for x in l if x != ' ']
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']
>>> l.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']

Related

Python: 2 Dimensional List

Problem
I need to populate a list from a text file. The list should be a 2 dimensional list. I have been doing a series of activities for my online class, and I can't seem to find and make the right codes for it. Any help would be much appreciated. The text file should look like this:
textfile.txt
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
expected output
twoDlist = [
['A', 'B', 'C', 'D', 'E', 'F'],
['G', 'H', 'I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P', 'Q', 'R'],
['S', 'T', 'U', 'V', 'W', 'X']
]
my current code
twoDlist = []
f = open("textfile.txt")
r = f.readlines()
for i in r:
twoDlist.append(i.strip())
print(twoDlist)
To fix your existing code, your i.strip() should be replaced by i.split()
Demo:
twoDlist = []
f = open("textfile.txt")
r = f.readlines()
for i in r:
twoDlist.append(i.split())
print(twoDlist)
Output:
[['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P', 'Q', 'R'], ['S', 'T', 'U', 'V', 'W', 'X']]
A better way of doing this would be:
twoDlist = []
with open("textfile.txt") as f:
twoDlist = [line.split() for line in f]
print(twoDlist)
This way the file management is handled for you.
What about this:
twoDlist = map(str.split, f)
Update:
As pointed out by zondo, if you are using Python3, you should:
twoDlist = list(map(str.split, f))
since map will return a map object instead of a list.

Can somebody explain what this function does and how it works?

One of the review questions for my midterm is to understand what this function does and I cannot read it because I don't understand where the parameters come from and how it works. Can somebody with programming experience help?
def enigma(numList, n, pos):
length = len(numList)
if pos == length:
print('Error')
return
newList = []
for i in range(pos):
newList = newList + [numList[i]]
newList = newList + [n]
tailLength = length - pos
counter = tailLength
while counter < length:
newList = newList + [numList[counter]]
counter = counter + 1
return newList
Many times trying some test data reveals the functionality quickly:
>>> enigma('abcdefghijklm', 'X', 0)
['X']
>>> enigma('abcdefghijklm', 'X', 1)
['a', 'X', 'm']
>>> enigma('abcdefghijklm', 'X', 2)
['a', 'b', 'X', 'l', 'm']
>>> enigma('abcdefghijklm', 'X', 3)
['a', 'b', 'c', 'X', 'k', 'l', 'm']
>>> enigma('abcdefghijklm', 'X', 4)
['a', 'b', 'c', 'd', 'X', 'j', 'k', 'l', 'm']
>>> enigma('abcdefghijklm', 'X', 12)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'X', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
>>> enigma('abcdefghijklm', 'X', 13)
Error
The code starts with an empty new_list and builds it up in three sections
The repeating the first pos number of elements
Adding the n element
Repeating the trailing pos number of elements
As pos becomes larger than the midpoint, the beginning and trailing elements sections cross over to repeat some items.

A list that returns the elements of a list of lists

I have a list:
word_list = ['dog', 'downvote', 'gestapo']
I would like this:
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
This is my code;
[list(word_list[j]) for j in range(len(word_list))]
This code returns this:
[['d', 'o', 'g'], ['d', 'o', 'w', 'n', 'v', 'o', 't', 'e'], ['g', 'e', 's', 't', 'a', 'p', 'o']]
Instead I tried this:
[(word_list[j])[k] for j in range(len(word_list)) for k in len(word_list[j])]
This returns an error: 'int' object is not iterable
I would like to rectify and update my final attempt so that I get the desired output.
If you want to preserve the original order of characters (as in the words from word_list):
def f(seq):
seen = set()
for x in (x for word in word_list for x in word):
if x not in seen:
seen.add(x)
yield x
list(f(word_list)) # ['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
If you don't, just construct the set using set comprehension:
{x for word in word_list for x in word} # {'e', 'd', 'n', 'a', 't', 'w', 'o', 'g', 'v', 's', 'p'}
Although I think you are all technically correct.
The right way to do it in python would probably be:
from itertools import chain
set(chain(*word_list))
k=[]
for j in [list(i) for i in word_list]:
k += j
print list(set(k))
>>>>['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
You could use reduce with operator.add, and a set.
>>> import operator
>>> words = ['dog', 'downvote', 'gestapo']
>>> set(reduce(operator.add, words))
set(['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v'])
If you want it to be a list:
>>> list(set(reduce(operator.add, words)))
['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v']
Note: it's not alphabetical order.
If the order is important, a simple way is to use(abuse?) an OrderedDict
>>> word_list = ['dog', 'downvote', 'gestapo']
>>> from collections import OrderedDict
>>> from itertools import chain
>>> OrderedDict.fromkeys(chain.from_iterable(word_list)).keys()
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']

Replacing one item in a list with two items

What is the simplest method for replacing one item in a list with two?
So:
list=['t' , 'r', 'g', 'h', 'k']
if I wanted to replace 'r' with 'a' and 'b':
list = ['t' , 'a' , 'b', 'g', 'h', 'k']
It can be done fairly easily with slice assignment:
>>> l = ['t' , 'r', 'g', 'h', 'k']
>>>
>>> pos = l.index('r')
>>> l[pos:pos+1] = ('a', 'b')
>>>
>>> l
['t', 'a', 'b', 'g', 'h', 'k']
Also, don't call your variable list, since that name is already used by a built-in function.
In case list contains more than 1 occurrences of 'r' then you can use a list comprehension or itertools.chain.from_iterable with a generator expression.But, if list contains just one such item then for #arshajii's solution.
>>> lis = ['t' , 'r', 'g', 'h', 'k']
>>> [y for x in lis for y in ([x] if x != 'r' else ['a', 'b'])]
['t', 'a', 'b', 'g', 'h', 'k']
or:
>>> from itertools import chain
>>> list(chain.from_iterable([x] if x != 'r' else ['a', 'b'] for x in lis))
['t', 'a', 'b', 'g', 'h', 'k']
Here's an overcomplicated way to do it that splices over every occurrence of 'r'. Just for fun.
>>> l = ['t', 'r', 'g', 'h', 'r', 'k', 'r']
>>> reduce(lambda p,v: p + list('ab' if v=='r' else v), l, [])
['t', 'a', 'b', 'g', 'h', 'a', 'b', 'k', 'a', 'b']
Now go upvote one of the more readable answers. :)

Sequence of letters in Python

Is there a built-in method / module in Python to generate letters such as the built-in constant LETTERS or letters constant in R?
The R built-in constant works as letters[n] where if n = 1:26 the lower-case letters of the alphabet are produced.
Thanks.
It's called string.ascii_lowercase.
If you wanted to pick n many random lower case letters, then:
from string import ascii_lowercase
from random import choice
letters = [choice(ascii_lowercase) for _ in range(5)]
If you wanted it as a string, rather than a list then use str.join:
letters = ''.join([choice(ascii_lowercase) for _ in range(5)])
You can use map as in the following:
>>> map(chr, range(65, 91))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> map(chr, range(97, 123))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> a = map(chr, range(65, 70))
>>> a
['A', 'B', 'C', 'D', 'E']
With list comprehensions and reference from the above, there is another method:
>>> [chr(x) for x in range(97, 123)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Yet another way to do it which will give you directly a string:
>>> bytearray(range(97,123)).decode("utf-8")
u'abcdefghijklmnopqrstuvwxyz'
(it works with both python2 and python3, of course the u prefix won't be visible if it's python 3)
You can obviously tranform that string into a list like in other answers if that is what you prefer, for instance with:
>>> [x for x in bytearray(range(97,123)).decode("utf-8")]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
It is also very easy to change it to pick n random letters (repetition allowed):
>>> import random
>>> n = 10
>>> bytearray(random.randint(97, 122) for x in range(n)).decode('utf-8')
'qdtdlrqidx'
Or without repetition:
>>> import random
>>> n = 10
>>> bytearray(random.sample(range(97, 123),n)).decode('utf-8')
'yjaifemwbr'

Categories

Resources