(Python) Replace array of string elements - python-3.x

I want to replace an array of string elements,but have a problem:
This is correct!!
However,this is error:
It seem replace first char....
Thanks to your help.

you have to specify dtype to get the expected behavior, else it will choose minimum size,
i think it is choosing chararray and you are trying add numbers/strings.
either use astype or numpy.array(data, dtype="") to set dtype, look at the syntax of numpy.arry below
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
set dtype to string/integer/float whatever you need, refere doucmentation for exact use

I suppose you want to replace some strings in the list with some numbers. You can do this easily with list comprehension like this.
data = ['C', 'C', 'W', 'C', 'H', 'H', 'W', 'C', 'W', 'H']
data = [15 if x == 'C' else 30 if x == 'W' else x for x in data]
# Output : [15, 15, 30, 15, 'H', 'H', 30, 15, 30, 'H']

I think you are using numpy with method array https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.array.html
The constructure has dtype, If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
So:
>>> data
['C', 'W', 'C', 'C', 'W', 'H']
>>> values = numpy.array(data)
>>> values
array(['C', 'W', 'C', 'C', 'W', 'H'], dtype='<U1')
values with dtype='<U1', that mean unicode length 1
Solution is set dtype is Unicode with length you want:
>>> values = numpy.array(data, dtype='<U256')
>>> values
array(['C', 'W', 'C', 'C', 'W', 'H'], dtype='<U256')
>>> values[values=='C'] = 15
>>> values
array(['15', 'W', '15', '15', 'W', 'H'], dtype='<U256')
That's right!

Related

Grouping the same letters within a code in Python

I am trying to write a code where it outputs the number of consecutive letters that come after one another as it is running through list_. So all the outputs will start with 1 consecutive number followed by a second and a third if the following value is equivalent. So for example the order ['b','b','b',r] would produce the output of 1,2,3,1 as the consecutive list is disrupt by the upcoming r in the loop so it goes back to 1 consecutive int from 3.
Code for the consecutive bs and rs
list_ = ['b', 'r', 'b', 'r', 'b', 'r', 'b', 'r', 'b', 'b', 'b', 'r', 'b', 'b', 'r', 'r', 'b', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'r']
for k, gp in groupby(list_):
print(k,list(gp))
This is rle:
What you are looking for is:
from itertools import groupby
rle = lambda x : [k for i,j in groupby(x) for k in range(1,len(list(j)) + 1)]
print(rle(['b','b','b','r']))
[1, 2, 3, 1]
Simple one-liner:
alist = ['b', 'b', 'b', 'r']
print([idx for k, group in itertools.groupby(alist)
for idx, v in enumerate(group, start=1)])
Output:
[1, 2, 3, 1]

How to convert a string to a list of characters in Python?

I know the string.split() function. What I want is to convert a particular word into a list. For eg converting a string 'python' to a list ['p', 'y', 't', 'h', 'o', 'n'].
In Python, you have to keep in mind that there are several data types which are iterables. In practice, this means you can go through each element one by one. Strings are no different:
>>> var = 'python'
>>> var[0]
p
>>> var[1]
y
The easiest way to construct a list out of an iterable is by using list:
>>> var = 'python'
>>> new_var = list(var)
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']
But it is not the only way, for example, you could use list-comprehensions to achieve the same (not that I advise you to use them)
>>> var = 'python'
>>> new_var = [c for c in var]
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']
Keeping in mind the idea of iterables is very useful because you can also transform your variable to other data types, such as a set:
>>> var = 'python'
>>> new_var = set(var)
>>> print(new_var)
{'o', 'y', 't', 'n', 'h', 'p'}
Which for the word Python is not very impressive, but if you use another one:
>>> var = 'mississippi'
>>> new_var = set(var)
>>> new_var
{'p', 'i', 's', 'm'}
You just get the used letters.

problems with a random number/letter generating script using the python random module

So I'm a bit of a Python beginner and I am wondering if there is a way to modify or fix this script so that it generates random number/letter sequences. I think I've got the actual generation solved, but I need some help on how to print the result to the console. Here is my code:
def main():
import random
random.random() * 10
myList = ["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"]
random.choice(myList)
print(random.random() * 10 + random.choice(myList))
main()
Can any of you guys help me out? as I said before, I am a beginner, so it might be a basic mistake and examples in answers would be great.
Error edited in:
line 9, in main
print(random.random() * 10 + random.choice(myList))
TypeError: unsupported operand type(s) for +: 'float' and 'str'
If you want to print a float, make a string from it:
def main():
import random
# random.random() * 10 # does nothing, you do not use the return
myList = ["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"]
# random.choice(myList) # does nothing, you do not use the return
print(str(random.random() * 10) + random.choice(myList))
# prints a [0.0-1.0[ * 10 + one character
main()
You can benefit from using a constant from string instead of your list - and probably want to use some other functions to draw from the list:
import string
import random
# prints random 20 lowercase chars w/o repeat
print(random.sample(string.ascii_lowercase,20)) # see doku for sample()
# print random 20 lowercase chars with repeat
print(random.choices(string.ascii_lowercase,k=20)) # see doku for choices()
# prints the same char multiple times
print(random.choice(string.ascii_lowercase) * random.randint(5,20))
Output:
['i', 'q', 's', 'z', 'g', 'v', 'r', 'j', 'h', 'u', 'y', 'p'
, 'n', 't', 'k', 'c', 'm', 'a', 'x', 'd']
['f', 'x', 'u', 'x', 'a', 'l', 'f', 'u', 'l', 'x', 'j', 'i'
, 'v', 'f', 'd', 'u', 'l', 'x', 'j', 'w']
rrrrrrrr # this one varies in char and amounts...
Doku of random - functions read up about sample, choices and random
Doku of string - constants
your lower case list is already a constant there.

How to create a list from another list in python

I am very new to python and i was stuck with this. I need to create a list of lists that is
formed from this list c: ['asdf','bbnm','rtyu','qwer'].
I need to create something like this:
b: [['a','s','d','f'],['b','b','n','m'],['r','t','y','u'],['q','w','e','r']]
I tried using a for-loop, but it is not working out. I don't know what mistake I am making.
You can use a list comprehension with list():
>>> c = ['asdf','bbnm','rtyu','qwer']
>>>
>>> b = [list(s) for s in c]
>>> b
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]
Notice that calling list() with a string argument returns a list containing the characters of that string:
>>> list('abc')
['a', 'b', 'c']
What we're doing above is applying this to every element of the list via the comprehension.
Use map function.
>>> a= ['asdf','bbnm','rtyu','qwer']
>>> map(list ,a )
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]
>>>
You could do something that's easier to understand:
b = []
for x in c:
list(x).append(b)

Comparing lists, is the subset list within the first list

How do I write a syntax for something like this?
if our list 1 = ['F', 'W', 'I', 'N', 'T', 'E', 'R', 'S']
our second list looks like = ['WINTER']
how would I write that list 1 contains a sequence of strings WINTER?
You could convert both to sets and use issubset ?
>>> list1
['F', 'W', 'I', 'N', 'T', 'E', 'R', 'S']
>>> list2
['W', 'I', 'N', 'T', 'E', 'R']
>>> set(list2).issubset(set(list1))
True
Or maybe convert them both to sets and then test list2 - list1 ?
Or (taken straight from the docs):
{x for x in list2 if x not in list1}

Resources