Create a list of consequential alphanumeric elements - python

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)

Related

Create list of tuples from two lists

I have two lists of coordinates:
[37.773972, -122.431297]
[37.773972, -122.45]
I want to create a list of tuples like so:
[(37.773972, -122.431297), (37.773972, -122.45)]
I've tried using zip but that merges the two.
thanks
>>> lst1 = [37.773972, -122.431297]
>>> lst2 = [37.773972, -122.45]
>>> res = [tuple(lst1), tuple(lst2)]
>>> res
[(37.773972, -122.431297), (37.773972, -122.45)]
How about this:
l1 = [37.773972, -122.431297]
l2 = [37.773972, -122.45]
merged = [tuple(l1), tuple(l2)]
print(merged) # [(37.773972, -122.431297), (37.773972, -122.45)]
list1 = [37.773972, -122.431297]
list2 = [37.773972, -122.45]
tup=[tuple(list1),tuple(list2)]
print(tup)
You can convert a list into tuple using tuple(list name).
Like:
def convert(list):
return tuple(list)
list = [a, c, b, d]
print(convert(list))
Here I define a function which is stored as a list and then I return it as a tuple. I give the input for list and finally when I print the defined function, It displays a tuple format of the list given.

Join characters from list of strings by index

For example, I have the following list.
list=['abc', 'def','ghi','jkl','mn']
I want to make a new list as:
newList=['adgjm','behkn','cfil']
picking every first character of each element forming a new string then appending into the new list, and then with the second character of every element and so on:
Thanks for the help.
One way is zipping the strings in the list, which will interleave the characters from each string in the specified fashion, and join them back with str.join:
l = ['abc', 'def','ghi','jkl']
list(map(''.join, zip(*l)))
# ['adgj', 'behk', 'cfil']
For strings with different length, use zip_longest, and fill with an empty string:
from itertools import zip_longest
l = ['abcZ', 'def','ghi','jkl']
list(map(''.join, zip_longest(*l, fillvalue='')))
# ['adgj', 'behk', 'cfil', 'Z']
You can try this way:
>>> list1 =['abc', 'def','ghi','jkl']
>>> newlist = []
>>> for args in zip(*list1):
... newlist.append(''.join(args))
...
>>> newlist
['adgj', 'behk', 'cfil']
Or using list comprehension:
>>> newlist = [''.join(args) for args in zip(*list1)]
>>> newlist
['adgj', 'behk', 'cfil']
You can try this:
list=['abc', 'def','ghi','jkl']
n = len(list[0])
newList = []
i = 0
for i in range(n):
newword = ''
for word in list:
newword += word[i]
newList.append(newword)
print(newList)

How to remove item in list in list with list comprehension

I have a large list like this:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
I'm trying to remove all numbers within the lists of this list. So I made a list of numbers as strings from 1 to 100:
def integers(a, b):
return list(range(a, b+1))
numb = integers(1,100)
numbs = []
for i in range(len(numb)):
numbs.append(str(numb[i])) # strings
numbs = ['1','2',....'100']
How can I iterate through lists in mylist and remove the numbers in numbs? Can I use list comprehension in this case?
If number is always in the end in sublist
mylist = [ x[:-1] for x in mylist ]
mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick.
However, this isn't quite what you've asked. Nothing was actually removed from mylist, we've just built an entirely new list and reassigned it to mylist. Same logical result, though.
If numbers are always at the end and only once, you can remove the last item like:
my_new_list = [x[:-1] for x in mylist]
If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]
I would also recommend to generate the list of interger as follow :
integer_list = list(map(str, range(1, 100)))
I hope it helps :)
Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]
If you have the following list:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]
Using list comprehension to remove element in numbs
[[l for l in ls if l not in numbs] for ls in mylist]
This is a more general way to remove digit elements in a list
[[l for l in ls if not l.isdigit()] for ls in mylist]

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()

List Comprehensions and Conditions?

I am trying to see if I can make this code better using list comprehensions.
Lets say that I have the following lists:
a_list = [
'HELLO',
'FOO',
'FO1BAR',
'ROOBAR',
'SHOEBAR'
]
regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE),
lambda x: re.search(r'RO', x, re.IGNORECASE)]
I basically want to add all the elements that do not have any matches in the regex_list into another list.
E.g. ==>
newlist = []
for each in a_list:
for regex in regex_list:
if(regex(each) == None):
newlist.append(each)
How can I do this using list comprehensions? Is it even possible?
Sure, I think this should do it
newlist = [s for s in a_list if not any(r(s) for r in regex_list)]
EDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list that doesn't match all the regexes - and what's more, it adds each string once for each regex that it doesn't match. My list comprehension does what I think you meant, which is add only one copy of each string that doesn't match any of the regexes.
I'd work your code down to this:
a_list = [
'HELLO',
'FOO',
'FO1BAR',
'ROOBAR',
'SHOEBAR'
]
regex_func = lambda x: not re.search(r'(FOO|RO)', x, re.IGNORECASE)
Then you have two options:
Filter
newlist = filter(regex_func, a_list)
List comprehensions
newlist = [x for x in a_list if regex_func(x)]

Categories

Resources