Generating a list of consecutive numbers as strings [duplicate] - python

This question already has answers here:
Generate string of numbers python
(2 answers)
Closed 2 years ago.
I would like to generate a list of numbers such as this:
['1','2','3','4','5','6']
but all I can seem to get is:
[1, 2, 3, 4, 5, 6]
using this code:
values = list(range(1,7))
Is there some easy way to generate a list of consecutive numbers, that are within apostrophes, since I want the code to treat them like a string.
I have tried:
values = str(list(range(1,7)))
but that just gave me the same result as above.

>>> [str(i) for i in range(1,7)]
['1', '2', '3', '4', '5', '6']

The comprehension proposed by #CoryKramer has you covered, but given your attempts, you might be looking for:
>>> list(map(str, range(1, 7)))
['1', '2', '3', '4', '5', '6']

Try the following:
list(map(str, range(1,7)))

Related

How to sort a list of integers that are stored as string in python [duplicate]

This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 2 years ago.
I tried to sort a list of string that are actually integers but i do not get the right sort value. How do i sort it in a way that it is sorted according to the integer value of string ?
a = ['10', '1', '3', '2', '5', '4']
print(sorted(a))
Output:
['1', '10', '2', '3', '4', '5']
Output wanted:
['1', '2', '3', '4', '5', '10']
We have to use the lambda as a key and make each string to int before the sorted function happens.
sorted(a,key=lambda i: int(i))
Output :
['1', '2', '3', '4', '5', '10']
More shorter way -> sorted(a,key=int). Thanks to #Mark for commenting.
So one of the ways to approach this problem is converting the list to a list integers by iterating through each element and converting them to integers and later sort it and again converting it to a list of strings again.
You could convert the strings to integers, sort them, and then convert back to strings. Example using list comprehensions:
sorted_a = [str(x) for x in sorted(int(y) for y in a)]
More verbose version:
int_a = [int(x) for x in a] # Convert all elements of a to ints
sorted_int_a = sorted(int_a) # Sort the int list
sorted_str_a = [str(x) for x in sorted_int_a] # Convert all elements of int list to str
print(sorted_str_a)
Note: #tedd's solution to this problem is the preferred solution to this problem, I would definitely recommend that over this.
Whenever you have a list of elements and you want to sort using some property of the elements, use key argument (see the docs).
Here's what it looks like:
>>> a = ['10', '1', '3', '2', '5', '4']
>>> print(sorted(a))
['1', '10', '2', '3', '4', '5']
>>> print(sorted(a, key=lambda el: int(el)))
['1', '2', '3', '4', '5', '10']

Convert mixed list to string [duplicate]

This question already has an answer here:
How to join mixed list (array) (with integers in it) in Python?
(1 answer)
Closed 3 years ago.
I have the list below, which contains strings and integers. How do I make a string of them? Tried to use
''.join(l)
but it does't work, because there are integers on the list(specifically, L[1] is an integer, and the others are all strings.). Can you help?
L=['1', 9, ':', '0', '5', ':', '4', '5']
#expected "19:05:45"
You can convert each number in the list into a string with a for loop or list comprehension. Like so:
l = ['1', 9, ':', '0', '5', ':', '4', '5']
''.join([str(x) for x in l])
'19:05:45'
Generators are perfect in this case:
>>> l = ['1', 9, ':', '0', '5', ':', '4', '5']
>>> ''.join(str(x) for x in l)
'19:05:45'
This looks the same as a list comprehension but does not require the creation of another list instance.
Just map all the elements to string before joining.
>>> ''.join(map(str,['1', 9, ':', '0', '5', ':', '4', '5']))
'19:05:45'
You can do it in a for loop
list_str = ''
for i in l:
list_str += str(i)
Or a with a list comprehension
list_str = ''.join([str(i) for i in l])

What does the "x for x in" syntax mean? [duplicate]

This question already has answers here:
Explanation of how nested list comprehension works?
(11 answers)
Closed 5 years ago.
What actually happens when this code is executed:
text = "word1anotherword23nextone456lastone333"
numbers = [x for x in text if x.isdigit()]
print(numbers)
I understand, that [] makes a list, .isdigit() checks for True or False if an element of string (text) is a number. However I am unsure about other steps, especially: what does that "x" do in front of for loop?
I know what the output is (below), but how is it done?
Output: ['1', '2', '3', '4', '5', '6', '3', '3', '3']
This is just standard Python list comprehension. It's a different way of writing a longer for loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.
See this for more info on list comprehension.

Nesting List Comprehension [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 5 years ago.
I frequently run into a problem where I'm trying to make a list of lists of a certain length from a string.
This is an example where I have a string, but would like to make a list of lists of length 3:
x = '123456789'
target_length = 3
new = [i for i in x]
final = [new[i:i+target_length] for i in range(0, len(x), target_length)]
print(final)
Output:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
So, this works, but feels so clunky.
Is there a better way to combine these arguments into one line or do you think that would make the code unreadable?
If you want to do it in one line you can just create the lists inside your comprehension:
x = '123456789'
target_length = 3
[list(x[i:i+target_length]) for i in range(0, len(x), target_length)]
>> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
This does it in one line:
f2 = [[x[(j * target_length) + i] for i in range(target_length)] for j in range(target_length)]

How to prepend all list elements into another list [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Merge two lists in python?
How can I prepend list elements into another list?
A = ['1', '2']
B = ['3', '4']
A.append(B)
print A
returns
['1', '2', ['3', '4']]
How can I make it
['1', '2', '3', '4']?
A.extend(B)
or
A += B
This text added to let me post this answer.
list.extend, for example, in your case, A.extend(B).
this can also be done as
for s in B:
A.append(B)
of course A.extend(B) does the same work but using append we need to add in the above f

Categories