Could you say me, how to write a function, which takes as its (one an only) argument a list of numbers and returns a list of string representations of those numbers?
For example toNum([1, 2, 3, 4]) returns ["1", "2", "3", "4"].
def to_num(a):
return map(str, a)
print to_num([1, 2, 3, 4])
prints
['1', '2', '3', '4']
using list comprehension:
def stringify(input):
return [str(num) for num in input]
Adrien already gave you an elegant answer:
def stringify(input):
return [str(num) for num in input]
That works perfectly, but if you intend to only iterate through the representations (and don't need to keep the whole list in memory for any other reason), you should instead do:
(str(num) for num in the_list)
The parenthesis instead of the brackets indicate a generator expression, just as iterable as a list, but won't fully expand on creation. This may be important if your list is large.
You just have to supply the parameters in the function call
def to_num(*numbers):# with the * you can enter as many parameters as you want
return [str(x) for x in numbers]
Related
I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:
sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.
def sort_item_list_by_author(self,new_item_list):
new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line
item11=Item("Broken Wing","Sarojini Naidu",2012)
item12=Item("Guide","R.K.Narayanan",2001)
item13=Item("Indian Summers","John Mathews",2001)
item14=Item("Innocent in Death","J.D.Robb",2010)
item15=Item("Life of Pi","Yann Martel",2010 )
item16=Item("Sustainability","Johny",2016)
item17=Item("Look Ahead","E.M.Freddy",2012 )
new_item_list=[item11,item12,item13,item14,item15,item16,item17]
new_item_list_sorted=library.sort_item_list_by_author(new_item_list)
lambda you are talking about is the key to the sort function, which means that it is being you used to compare the values in the list.
lambda x:''.join(e for e in x.get_author_name() if e.isalnum()
So for every element of the list, this lambda function is called. Here x represents the parameter of the lambda function(in this case, it is list item).
Now the body of the lambda function is pretty simple in itself, we get the author name, and loop over it character by character, and select only those characters which are alpha-numeric(means we are ignoring spaces and all), then we join all the obtained chars in one string.
Using the lambda function, for all the items in the list, such strings(alpha-num part of author's name) are created, which is used for sorting out the list.
The lambda translates to something like this:
x = item() #fill the fields here
s = ''
for e in x.get_author_name():
if e.isalnum():
s += e
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.Let's see an example.
>>> addition=lambda x1,x2:x1+x2
>>> subtraction=lambda x1,x2:x1-x2
>>> addition(10,20)
30
>>> subtraction(10,20)
-10
>>> #there is another way also
>>>(lambda num1, num2: num1+num2)(10,20)
30
Now Suppose we have a list of items(integers and strings with numeric contents)
numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
Now I am using sorted function to sort it, You can use sort also but as we know sort function alters the original data but the sorted returns a new sorted list
>>> numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
>>> sorted(numbers)
[1, 3, 4, '-1', '-11', '2', '5', '8']
>>>
But this is not expected answer
['-11', '-1', 1, '2', 3, 4, '5', '8']
so here we've to used to key keyword as a argument
>>> sorted(numbers, key=int)
['-11', '-1', 1, '2', 3, 4, '5', '8']
>>> sorted(['There', 'are','some', 'sort', 'words'], key=lambda word: word.lower())
['are', 'some', 'sort', 'There', 'words']
Which is same as
sorted(['There', 'are','some', 'sort', 'words'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element
key=str.lower The default value is None (compare the elements directly)
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 8 months ago.
The community reviewed whether to reopen this question 17 days ago and left it closed:
Original close reason(s) were not resolved
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in order to join it with the list?
Do I need to do the following for every integer value:
myList.append(str(myfunc()))
Is there a more Pythonic way to solve casting problems?
Calling str(...) is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:
print(','.join(str(x) for x in list_of_ints))
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
The map function in python can be used. It takes two arguments. The first argument is the function which has to be used for each element of the list. The second argument is the iterable.
a = [1, 2, 3]
map(str, a)
['1', '2', '3']
After converting the list into a string you can use the simple join function to combine the list into a single string
a = map(str, a)
''.join(a)
'123'
There are three ways of doing this.
let say you have a list of integers
my_list = [100,200,300]
"-".join(str(n) for n in my_list)
"-".join([str(n) for n in my_list])
"-".join(map(str, my_list))
However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
For example:
lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]
lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']
As to me, I want to add a str before each str list:
# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']
Or single list:
lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
How come no-one seems to like repr?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr
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']]
If you have the following code, how exactly is it following the documentation: map(function, iterable,...)?
x = sorted(map(int, dat[0].split()))
Is int a function and if so, why isn't it expressed as such?
int is a constructor so it's callable so you can use it with map
In your case dat[0] is as string, and split() generates a list of strings, by splitting the input string at whitespaces.
Eg
"1 11".split()
returns
["1", "11"]
The map function has two input arguments:
The first argument is something which can be called (in Python you say it is a callable), eg a function. int is not realy a function but such a thing (Python slang: it is an object).
Eg int("3") return 3. So int when applied to a string tries to convert this string to an integer, and gives the integer value back.
The second argument is something you can iterate over, in your case it is a list.
If you then call the map function, the first argument is applied to all elements from the second argument.
So
map(int, ["1", "11"])
returns
[1, 11]
If you combine what I explained you understand that
map(int, "1 11".split())
returns
[1, 11]
When you ask "why isn't it expressed as such" I suppose you mean, why doesn't it have brackets like a function? The answer is that if you put the brackets in then you get what the function does instead of the function itself. Compare what happens when you enter int() versus int.
Think of it like this
def map( function, iterable ):
return ( function(x) for x in iterable )
In x = sorted(map(int, dat[0].split())) the function, int, is being named, not evaluated. This code provides a function object to the map function. The map function will evaluate the given function.
The syntax of map in the simplest form is:
map(func, sequence)
It will apply the function "func" on each element of the sequence and return the sequence. Just in case you don't know, int() is a function.
>>> int(2.34)
2
>>> int("2")
2
>>> a = ["1", "101", "111"]
>>> map(int, a)
[1, 101, 111]
Now, I will give you my implementation of map().
>>> for index in range(len(a)):
... a[index] = int(a[index])
...
>>> a
[1, 101, 111]
If you have understood the concept, let's take a step further. We converted the strings to int using base 10 (which is the default base of int() ). What if you want to convert it using base 2?
>>> a = ["1", "101", "111"]
>>> for index in range(len(a)):
... a[index] = int(a[index], 2) # We have an additional parameter to int()
...
>>> a
[1, 5, 7]
To get the same result using map(), we will use a lambda function
>>> a = ["1", "101", "111"]
>>> map(lambda x: int(x, 2), a)
[1, 5, 7]
What is the easiest way to convert list with str into list with int in Python?
For example, we have to convert ['1', '2', '3'] to [1, 2, 3]. Of course, we can use a for loop, but it's too easy.
Python 2.x:
map(int, ["1", "2", "3"])
Python 3.x (in 3.x, map returns an iterator, not a list as in 2.x):
list(map(int, ["1", "2", "3"]))
map documentation: 2.6, 3.1
[int(i) for i in str_list]
You could also use list comprehensions:
new = [int(i) for i in old]
Or the map() builtin function:
new = map(int, old)
Or the itertools.imap() function, which will provide a speedup in some cases but in this case just spits out an iterator, which you will need to convert to a list (so it'll probably take the same amount of time):
import itertools as it
new = list(it.imap(int, old))
If your strings are not only numbers (ie. u''), you can use :
new = [int(i) for i in ["1", "2", "3"] if isinstance(i, int) or isinstance(i, (str, unicode)) and i.isnumeric()]
If It is array and has installed numpy. We can used below code as well.
import numpy as np
np.array(['1', '2', '3'],dtype=int)