python add string to the start of each element in array - python

In the following i have an array where for each element a string should be added at the start and not append ,how can i do this
a=["Hi","Sam","How"]
I want to add "Hello" at the start of each element so that the output will be
Output:
a=["HelloHi","HelloSam","HelloHow"]

This works for a list of strings:
a = ['Hello'+b for b in a]
and this works for other objects too (uses their strings representation):
a = ['Hello{}'.format(b) for b in a]
Example:
a = ["Hi", "Sam", "How", 1, {'x': 123}, None]
a = ['Hello{}'.format(b) for b in a]
# ['HelloHi', 'HelloSam', 'HelloHow', 'Hello1', "Hello{'x': 123}", 'HelloNone']

a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a

or you can use map:
map('Hello{0}'.format,a)

Another option:
>>> def say_hello(foo):
... return 'Hello{}'.format(foo)
...
>>> map(say_hello,['hi','there'])
['Hellohi', 'Hellothere']

Related

How to convert an integer to a list in python?

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].
I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
If you are trying to convert in to string, use str()
>>> str(1234)
'1234'
If you are trying to put your int in a list, use []:
>>> var = 1234
>>> [var]
[1234]
or do:
>>> l = []
>>> l.append(var)
>>> l
[1234]
Just cover it with brackets:
a=1243
a=[a]
or create a list and append a
b = []
b.append(a) # or you could do b=[a]

Python: Split a list into multiple lists based on a subset of elements [duplicate]

This question already has answers here:
Splitting a list based on a delimiter word
(4 answers)
Closed 4 years ago.
I am trying to split a list that I have into individual lists whenever a specific character or a group of characters occur.
eg.
Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf'...]
I want to break this list and save it into a sublist whenever I encounter an 'L' or an 'R'
Desired Result:
sublist_1 = ['abcd 1233','cdgfh3738','hryg21']
sublist_2 = ['gdyrhr657','abc31637']
sublist 3 = ['7473hrtfgf'...]
Is there a built in function or a quick way to do this ?
Edit: I do not want the delimiter to be in the list
Use a dictionary for a variable number of variables.
In this case, you can use itertools.groupby to efficiently separate your lists:
L = ['abcd 1233','cdgfh3738','hryg21','**L**',
'gdyrhr657','abc31637','**R**','7473hrtfgf']
from itertools import groupby
# define separator keys
def split_condition(x):
return x in {'**L**', '**R**'}
# define groupby object
grouper = groupby(L, key=split_condition)
# convert to dictionary via enumerate
res = dict(enumerate((list(j) for i, j in grouper if not i), 1))
print(res)
{1: ['abcd 1233', 'cdgfh3738', 'hryg21'],
2: ['gdyrhr657', 'abc31637'],
3: ['7473hrtfgf']}
Consider using one of many helpful tools from a library, i.e. more_itertools.split_at:
Given
import more_itertools as mit
lst = [
"abcd 1233", "cdgfh3738", "hryg21", "**L**",
"gdyrhr657", "abc31637", "**R**",
"7473hrtfgf"
]
Code
result = list(mit.split_at(lst, pred=lambda x: set(x) & {"L", "R"}))
Demo
sublist_1, sublist_2, sublist_3 = result
sublist_1
# ['abcd 1233', 'cdgfh3738', 'hryg21']
sublist_2
# ['gdyrhr657', 'abc31637']
sublist_3
# ['7473hrtfgf']
Details
The more_itertools.split_at function splits an iterable at positions that meet a special condition. The conditional function (predicate) happens to be a lambda function, which is equivalent to and substitutable with the following regular function:
def pred(x):
a = set(x)
b = {"L", "R"}
return a.intersection(b)
Whenever characters of string x intersect with L or R, the predicate returns True, and the split occurs at that position.
Install this package at the commandline via > pip install more_itertools.
#Polyhedronic, you can also try this.
>>> import re
>>> Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf']
>>>
>>> s = ','.join(Main_list)
>>> s
'abcd 1233,cdgfh3738,hryg21,**L**,gdyrhr657,abc31637,**R**,7473hrtfgf'
>>>
>>> items = re.split('\*\*R\*\*|\*\*L\*\*', s)
>>> items
['abcd 1233,cdgfh3738,hryg21,', ',gdyrhr657,abc31637,', ',7473hrtfgf']
>>>
>>> output = [[a for a in item.split(',') if a] for item in items]
>>> output
[['abcd 1233', 'cdgfh3738', 'hryg21'], ['gdyrhr657', 'abc31637'], ['7473hrtfgf']]
>>>
>>> sublist_1 = output[0]
>>> sublist_2 = output[1]
>>> sublist_3 = output[2]
>>>
>>> sublist_1
['abcd 1233', 'cdgfh3738', 'hryg21']
>>>
>>> sublist_2
['gdyrhr657', 'abc31637']
>>>
>>> sublist_3
['7473hrtfgf']
>>>

Create a list of consequential alphanumeric elements

I have
char=str('DOTR')
and
a=range(0,18)
How could I combine them to create a list with:
mylist=['DOTR00','DOTR01',...,'DOTR17']
If I combine them in a for loop then I lose the leading zero.
Use zfill:
>>> string = "DOTR"
>>> for i in range(0, 18):
... print("DOTR{}".format(str(i).zfill(2)))
...
DOTR00
DOTR01
DOTR02
DOTR03
DOTR04
DOTR05
DOTR06
DOTR07
DOTR08
DOTR09
DOTR10
DOTR11
DOTR12
DOTR13
DOTR14
DOTR15
DOTR16
DOTR17
>>>
And if you want a list:
>>> my_list = ["DOTR{}".format(str(i).zfill(2)) for i in range(18)]
>>> my_list
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
>>>
You can do it using a list comprehension like so:
>>> mylist = [char+'{0:02}'.format(i) for i in a]
>>> mylist
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
Simply use list comprehension and format:
mylist = ['DOTR%02d'%i for i in range(18)]
Or given that char and a are variable:
mylist = ['%s%02d'%(char,i) for i in a]
You can, as #juanpa.arrivillaga also specify it as:
mylist = ['{}{:02d}'.format(char,i) for i in a]
List comprehension is a concept where you write an expression:
[<expr> for <var> in <iterable>]
Python iterates over the <iterable> and unifies it with <var> (here i), next it calls the <expr> and the result is appended to the list until the <iterable> is exhausted.
can do like this
char = str('DOTR')
a=range(0,18)
b = []
for i in a:
b.append(char + str(i).zfill(2))
print(b)

Converting Strings to two lists in Python

(This is probably really simple, but) Say I have this input as a string:
"280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
and I want to separate each coordinate point onto separate lists, for each x and y value, so they'd end up looking like this:
listX = [280.2, 323.1, 135.8, 142.9]
listY = [259.8, 122.5, 149.5, 403.5]
I'd need this to be able to start out with any size string, thanks in advance!
Copy and paste this and it should work:
s_input = "280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
listX = [float(x.split(',')[0]) for x in s_input.split()]
listY = [float(y.split(',')[1]) for y in s_input.split()]
This would work.
my_string="280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
listX =[item.split(",")[0] for item in my_string.split()]
listY=[item.split(",")[1] for item in my_string.split()]
or
X_list=[]
Y_list=[]
for val in [item.split(",") for item in my_string.split()]:
X_list.append(val[0])
Y_list.append(val[1])
Which version to use would probably depend on your personal preference and the length of your string.
Have a look at the split method of strings. It should get you started.
You can do the following:
>>> a ="280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
>>> b = a.split(" ")
>>> b
['280.2,259.8', '323.1,122.5', '135.8,149.5', '142.9,403.5']
>>> c = [ x.split(',') for x in b]
>>> c
[['280.2', '259.8'], ['323.1', '122.5'], ['135.8', '149.5'], ['142.9', '403.5']]
>>> X = [ d[0] for d in c]
>>> X
['280.2', '323.1', '135.8', '142.9']
>>> Y = [ d[1] for d in c]
>>> Y
['259.8', '122.5', '149.5', '403.5']
There's a magical method call str.split, which given a string, splits by a delimiter.
Assume we have the string in a variable s.
To split by the spaces and make a list, we would do
coords = s.split()
At this point, the most straightforward method of putting it into the lists would be to do
listX = [float(sub.split(",")[0]) for sub in coords]
listY = [float(sub.split(",")[1]) for sub in coords]
You can use a a combination of zip and split with a list comprehension:
s = "280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
l = zip(*[a.split(',') for a in s.split()])
This will return a list of 2 tuples.
To get lists instead, use map on it.
l = map(list, zip(*[a.split(',') for a in s.split()]))
l[0] and l[1] will have your lists.
if your list is huge, consider using itertools.izip()

Replacing an item in a python list by index.. failing?

Any idea why when I call:
>>> hi = [1, 2]
>>> hi[1]=3
>>> print hi
[1, 3]
I can update a list item by its index, but when I call:
>>> phrase = "hello"
>>> for item in "123":
>>> list(phrase)[int(item)] = list(phrase)[int(item)].upper()
>>> print phrase
hello
It fails?
Should be hELLo
You haven't initialised phrase (The list you were intending to make) into a variable yet. So pretty much you have created a list in each loop, it being the exact same.
If you were intending to actually change the characters of phrase, well that's not possible, as in python, strings are immutable.
Perhaps make phraselist = list(phrase), then edit the list in the for-loop. Also, you can use range():
>>> phrase = "hello"
>>> phraselist = list(phrase)
>>> for i in range(1,4):
... phraselist[i] = phraselist[i].upper()
...
>>> print ''.join(phraselist)
hELLo
>>> phrase = "hello"
>>> list_phrase = list(phrase)
>>> for index in (1, 2, 3):
list_phrase[index] = phrase[index].upper()
>>> ''.join(list_phrase)
'hELLo'
If you prefer one-liner:
>>> ''.join(x.upper() if index in (1, 2, 3) else x for
index, x in enumerate(phrase))
'hELLo'
Another answer, just for fun :)
phrase = 'hello'
func = lambda x: x[1].upper() if str(x[0]) in '123' else x[1]
print ''.join(map(func, enumerate(phrase)))
# hELLo
To make this robust, I created a method: (because I am awesome, and bored)
def method(phrase, indexes):
func = lambda x: x[1].upper() if str(x[0]) in indexes else x[1]
return ''.join(map(func, enumerate(phrase)))
print method('hello', '123')
# hELLo
consider that strings are immutable in python You can't modify existing string can create new.
''.join([c if i not in (1, 2, 3) else c.upper() for i, c in enumerate(phrase)])
list() creates a new list. Your loop creates and instantly discards two new lists on each iteration. You could write it as:
phrase = "hello"
L = list(phrase)
L[1:4] = phrase[1:4].upper()
print("".join(L))
Or without a list:
print("".join([phrase[:1], phrase[1:4].upper(), phrase[4:]]))
Strings are immutable in Python therefore to change it, you need to create a new string.
Or if you are dealing with bytestrings, you could use bytearray which is mutable:
phrase = bytearray(b"hello")
phrase[1:4] = phrase[1:4].upper()
print(phrase.decode())
If indexes are not consecutive; you could use an explicit for-loop:
indexes = [1, 2, 4]
for i in indexes:
L[i] = L[i].upper()

Categories

Resources