This question already has answers here:
Easiest way to join list of ints in Python?
(3 answers)
How can I convert each item in the list to string, for the purpose of joining them? [duplicate]
(9 answers)
Closed 1 year ago.
I want to convert a list to string e.g list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
would be list = '1234567890'
I tried ''.join() but this doesn't work since the list consists of integers
You need to convert each item to string first
''.join(str(x) for x in list)
As you have a list of int values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] (don't use builtin list for naming) you may convert them to str before with
a generator expression
result = ''.join(str(x) for x in values)
map function
result = ''.join(map(str, values))
you can try:
lst=[1,3,2,4,4]
list_string=''
for i in lst:
list_string+=str(i)
print(list_string)
note: you can not use list as variable.
Related
This question already has answers here:
Finding and replacing elements in a list
(10 answers)
Closed 2 years ago.
Is there a fancy method for replacing a specific value of a list with another value?
Like a shortcut for this:
>>> l = list(range(10))
>>> replacing = 3
>>> l[l.index(replacing)] = 4
>>> l
[0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
With the example I gave it's easy enough to do via the [l.index()], but when the list reference is a few dots away it starts getting ugly.
It would be so much prettier to do something like this:
>>> some.thing.very.far.away.list = list(range(10))
>>> some.thing.very.far.away.list.replace(3, 4)
Edit:
I forgot to say why.
I want to edit the same list, and only edit one of the values.
I'm actually kind of supprized that lists doesn't have a built-in method like list.replace(old, new[, max), considering that strings do and it seems like python has built-ins for just about everying.
Build a new list with a list comprehension:
new_items = [4 if x==3 else x for x in l]
You can modify the original list in-place if you want, but it doesn't actually save time:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if (item ==3 2):
items[index] = 4
you can assign "some.thing.very.far.away.list" to a temporary variable and apply replace function
some.thing.very.far.away.list = temp
something.very.far.away.list = temp.replace(x,y)
This can be a trick:
First define a dictionary with values you want to replace, than use a list comprehension using dictionary get with a default value.
You are passing el both as a key of the dictionary and as default value. If the key is found the corresponding value will be replaced otherwise the default value itself.
>>> l = [0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
>>> rpl = {1: 23, 6: 12}
>>> [rpl.get(el, el) for el in l]
[0, 23, 2, 4, 4, 5, 12, 7, 8, 9]
You can use map method to iterate and replace certain value.
syntax : map(function, iterable, ...)
The returned value from map() (map object) can then be passed to functions like list() (to create a list), set() (to create a set) and so on.
l = list(range(10))
replacing = 3
l = list(map(lambda x: 4 if x == replacing else x, l)) # iterating over list l and replacing certain value using map method and converting map object in to another list.
print(l)
output = [0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
it takes two parameter function and iterable. map() passes each item of the iterable to this function.
where lambda function takes argument x from sequence (l), assign 4 if x is equal to 4 .
to know more about map method Python map()
This question already has answers here:
Concatenating two range function results
(8 answers)
How can I generate a list of consecutive numbers? [duplicate]
(8 answers)
Closed 3 years ago.
in python is there a way to create of list that will skip numbers and will continue after skipping? something like the following code:
x = [1...3, 6...10]
print(x)
# [1,2,3,6,7,8,9,10]
Well its easy to write a for loop and then skip each defined index/value, or i can just use range, what I am looking for is a shorter more readable line. If not I can understand.
Simplest way to do this is to call range() and unpack result inside list assignment.
x = [*range(1, 4), *range(6, 11)]
Alternatively you can use itertools.chain:
>>> import itertools
>>> list(itertools.chain(range(1, 5), range(20, 25)))
[1, 2, 3, 4, 20, 21, 22, 23, 24]
If numpy is an option, you can use np.r_ to concatenate slice objects:
import numpy as np
np.r_[1:4, 6:11]
# array([ 1, 2, 3, 6, 7, 8, 9, 10])
You can turn it into a recursive function:
def recursive_ranges(ranges):
if len(ranges) == 1:
return list(range(*ranges[0]))
else:
return list(range(*ranges[0])) + recursive_ranges(ranges[1:])
You can then call this, specifying ranges as a list of lists:
ranges = [[1, 4], [6, 11]]
recursive_ranges(ranges)
# [1, 2, 3, 6, 7, 8, 9, 10]
Note the *ranges[0] is used to unpack the elements in ranges[0] into individual arguments. Essentially the recursive function keeps grabbing the first element of ranges, each element of which is a two-element array, and passing those numbers into the range() method as two different values instead of one array. That's what the * does, it unpacks the array. First call, you unpack [1, 4] into range(1, 4) and then append the next call of the recursive function to it.
Basically this unpacks into the following:
list(range(1, 4)) + list(range(6, 11))
but you get to use a much more compact syntax, just passing a list of lists.
This question already has answers here:
Formatting consecutive numbers
(5 answers)
Closed 5 years ago.
I am writing a program which generates a list of integers, for example:
[2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]
This list can be very long, but it contains many consecutive values, as seen in this example.
In order to store it (in a database), I would like to convert it to a formatted string, in the following format:
"2,5-10,15,18-20"
I already have in mind a solution, which is iterating through the whole list to detect consecutive values and building the string.
My question is: is there another, simpler way of doing this conversion in Python?
Not exactly simple, but this produces the desired results:
from itertools import groupby, count
from operator import itemgetter
a = [2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]
formatted = ','.join(str(x) if x == y else "{}-{}".format(x, y) for x, y in [itemgetter(0, -1)(list(g)) for k, g in groupby(a, lambda n, c = count(): n - next(c))])
print(formatted)
Which displays:
2,5-10,15,18-20
As far as I am aware, the solution you propose is the only option:
Iterate over items, storing the first number in the sequence
If the next number is not the next in the sequence, build "first-last" string and add to list of sequences.
No reason to store as string, can be stored as a list of strings instead
This question already has answers here:
How to make a function return a list of indices of the characters in the second string that appears in the first string?
(4 answers)
Closed 6 years ago.
def abc(a, b):
'''(str, str) -> list of int
>>> abc('ABCDEAADFET', 'ABCDE')
[0,1,2,3,4,5]
>>> abc('ABCDEAADFEABCDET', 'ABCDE')
[0,1,2,3,4,10,11,12,13,14]
>>> abc('SDFECAADFET', 'ABCDE')
[]
# how to do this ? especially the second case
# use a.find.()
Simple way to do it will be by creating a function as:
def my_function(my_string, my_substring):
len_substring = len(my_substring)
my_index = []
for i in range(len(my_string)-len_substring+1):
if my_string[i:i+len_substring] == my_substring:
my_index.extend(range(i, i+len_substring))
return my_index
Explanation:
Iterate your string to check the match for substring. If there is a match, add the corresponding indexes to the list.
Sample Run:
>>> my_function('ABCDEAADFET', 'ABCDE')
[0, 1, 2, 3, 4]
>>> my_function('ABCDEAADFEABCDET', 'ABCDE')
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
>>> my_function('SDFECAADFET', 'ABCDE')
[]
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 7 years ago.
I am producing a list of list by this code, it is just a condition for a column of a dataframe named lvl or "Level", then append the index of this condition values, so the problem that i got is that the order of appending is important to me,
for i in range(1,int(24-lvl)):
j=list2[(list2.lvl==(lvl+i))]
jj=[]
jj.append(j.index)
print itertools.chain(jj)
well for example, the answer should be:
[0,100,110,500,501,550,555,89,120,114]
but i get the same list but sorted
[0,89,100,110,114,120,500,501,550,555]
itertools.chain works for me. You need to unpack the list before passing it to chain method.
>>> l = [[1,5],[10,2],[6,9,3]]
>>> list(itertools.chain(*l))
[1, 5, 10, 2, 6, 9, 3]
You can simply do it with list comprehension:
>>> l = [[1,5],[10,2],[6,9,3]]
>>> l_out = [item for sub_l in l for item in sub_l]
>>> l_out
[1, 5, 10, 2, 6, 9, 3]