Actually quite simple question:
I've a python list like:
['1','2','3','4']
Just wondering how can I strip those single quotes?
I want [1,2,3,4]
Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:
map(int, your_list)
and
[int(value) for value in your_list]
See the documentation on map() and list comprehensions for more info.
If you want to leave the items in your list as strings but display them without the single quotes, you can use the following:
print('[' + ', '.join(your_list) + ']')
If that's an actual python list, and you want ints instead of strings, you can just:
map(int, ['1','2','3','4'])
or
[int(x) for x in ['1','2','3','4']]
Try this
[int(x) for x in ['1','2','3','4']]
[1, 2, 3, 4]
and to play safe you may try
[int(x) if type(x) is str else None for x in ['1','2','3','4']]
Related
i have list of strings
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
and i have prefix string :
/root
is there any pythonic way to add the prefix string to each element in the list
so the end result will look like this:
lst = ["/root/foo/dir/c-.*.txt","/root/foo/dir2/d-.*.svc","/root/foo/dir3/es-.*.info"]
if it can be done without iterating and creating new list ...
used:
List Comprehensions
List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or
iterable, or to create a subsequence of those elements that satisfy a
certain condition.
F=Strings
F-strings provide a way to embed expressions inside string literals,
using a minimal syntax. It should be noted that an f-string is really
an expression evaluated at run time, not a constant value. In Python
source code, an f-string is a literal string, prefixed with 'f', which
contains expressions inside braces. The expressions are replaced with
their values.
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
lst =[ f'{prefix}{path}' for path in lst]
print(lst)
I am not sure of pythonic, but this will be also on possible way
list(map(lambda x: '/root' + x, lst))
Here there is comparison between list comp and map List comprehension vs map
Also thanks to #chris-rands learnt one more way without lambda
list(map('/root'.__add__, lst))
Use list comprehensions and string concatenation:
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
print(['/root' + p for p in lst])
# ['/root/foo/dir/c-.*.txt', '/root/foo/dir2/d-.*.svc', '/root/foo/dir3/es-.*.info']
Just simply write:
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix="/root"
res = [prefix + x for x in lst]
print(res)
A simple list comprehension -
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
print([prefix + string for string in lst]) # You can give it a variable if you want
This question already has answers here:
how to change [1,2,3,4] to '1234' using python
(2 answers)
Closed 7 years ago.
I'm a Python beginner struggling to write code that uses the list myList = [['A','B','C'],[4,5,6],[7,8,9]] and generates the output below:
Input:
myList = [['A','B','C'],[4,5,6],[7,8,9]]
Expected output: (by line)
-A-B-C-
-4-5-6-
-7-8-9-
I've tried a few different things but am not sure how to approach the confluence of strings and integers in the same list.
I can get:
>>> for i in range (0,myList_len):
... print ("-".join(myList[i]))
...
A-B-C
But I can't get this to work for the numbers. Any help would be much appreciated!
You could use map to convert from int to str
for l1 in myList:
print '-' + '-'.join(map(str, l1)) + '-'
When you try to join numbers, you get the following error:
TypeError: sequence item 0: expected str instance, int found
This is because str.join() only works with str items in the iterable, but you pass it int objects instead.
So in order to properly join them, you need to convert them to strings first. You can either do that by calling str on every item using map, or by using a list comprehension:
>>> lst = [4, 5, 6]
>>> '-'.join(map(str, lst))
'4-5-6'
>>> '-'.join([str(x) for x in lst])
'4-5-6'
The "join" operator expects a list of strings, so you have to turn your numbers to strings first, using the "str" operator that turns anything into a string.
for l in myList:
print '-' + '-'.join([str(x) for x in l]) + '-'
join works on strings, not numbers. You need to convert:
print ("-".join(str(num) for num in myList[i]))
Now, just add the hyphens at start and finish, and you're done.
Try the following:
for sublist in myList:
print("-".join(map(str, sublist)))
The output is:
A-B-C
4-5-6
7-8-9
If you want leading and trailing hyphens as well, use:
for sublist in myList:
print("-" + "-".join(map(str, sublist)) + "-")
The output is:
-A-B-C-
-4-5-6-
-7-8-9-
The for loop iterates over the sublists. The map(str, sublist) call applies str to each element of the sublist, converting it to a string. Without this, your non-string entries (i.e., numbers) were causing errors when passed to join.
for example, i have a list below,
['Visa', 'Rogers', 'Visa']
if i want to convert it to a list of tuples, like
[('Visa',), ('Rogers',), ('Visa',)]
How can I convert it?
>>> [(x,) for x in ['Visa', 'Rogers', 'Visa']]
[('Visa',), ('Rogers',), ('Visa',)]
simple list comprehension will do the trick. make sure to have the , to specify single item tuples (you will just have the original strings instead)
Doing some kind of operation for each element can be done with map() or list comprehensions:
a = ['Visa', 'Rogers', 'Visa']
b = [(v,) for v in a]
c = map(lambda v: (v,), a)
print(b) # [('Visa',), ('Rogers',), ('Visa',)]
print(c) # [('Visa',), ('Rogers',), ('Visa',)]
Please keep in mind that 1-element-tuples are represented as (value,) to distinguish them from just a grouping/regular parantheses
I currently have a list that looks like the following:
list = ['325 153\n', '509 387\n', '419 397\n']
I am wondering how could i access these strings individually so i could use it in a function such as
for (x, y) in list:
where x is the first number of the string and y is the second number (separated by the space)
Is a good way to do this to turn the string into tuples somehow? I have tried using the 'split' function as i believe it is not valid for a list.
>>> a_list = ['325 153\n', '509 387\n', '419 397\n']
>>> [ i.split() for i in a_list ]
[['325', '153'], ['509', '387'], ['419', '397']]
You can iterate one the elements of the list:
for elem in list:
a, b = elem.split()[0], elem.split()[1]
a and b will be the elements and you can process them just as you wish.
[tuple(x.split()) for x in list]
this will return you a list of tuples
There is the split() method for string. Before using it you should use strip() to get rid of the training \n. At the end you can put both into a list comprehension:
for x, y in [item.strip().split(" ", 1) for item in lst]:
Note that I replace list with lst. list is a built-in type and should not be used as variable name.
Is there a Pythonic way to change the type of every object in a list?
For example, I have a list of objects Queries.
Is there a fancy way to change that list to a list of strings?
e.g.
lst = [<Queries: abc>, <Queries: def>]
would be changed to
lst = ['abc', 'def']
When str() is used on a Queries object, the strings I get are the ones in the second code sample above, which is what I would like.
Or do I just have to loop through the list?
Many thanks for any advice.
newlst = [str(x) for x in lst]
You could use a list comprehension.
Try this:
new_list = map(str, lst)
Try this (Python 3):
new_list = list(map(str, lst))
or
new_list = [str(q) for q in lst]