Python map element with character [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am new to python and i am trying to understand the map() function. Is there a better way of doing this
map(lambda x: x+"+" ,map(str,range(5)))
output : ['0+', '1+', '2+', '3+', '4+']

You can use the format-Method directly as map-argument:
map("{}+".format, range(5))

For most tasks like this, it is preferable to use a list comprehension, like so:
[str(i) + '+' for i in range(5)]
Here, you are constructing a list with each element depending only on the number i. Using str(i) + '+' is then one way to build the elements that you want. Another is '{} +'.format(i), but that is beside the point of using a list comprehension.
map vs. list comprehension
The map function is functionally equivalent to a restricted use of the list comprehension syntax. Consider the following generic examples, which will produce the same output:
list(map(fun, iterable))
[fun(el) for el in iterable]
In your example, you construct the function fun right there inside the map call using a lambda expression. The additional list() call is necessary in Python 3, as map returns a generator and not a list.

output = ['{}+'.format(i) for i in range(5)]
print output
['0+', '1+', '2+', '3+', '4+']

As you said you want in Map, You can map something like this:
print(list(map(lambda x:str(x)+'+',range(5))))
output:
['0+', '1+', '2+', '3+', '4+']
Additional info :
map() is a function with two arguments :
map(g, iterable)
first argument function is a function and the second a sequence.
Python 3 map is equivalent to the generator expression
(g(x) for x in iterable)

Related

How to map two lists in python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am looking for a optimal solution where i can map elements of multiple lists and display output in following format given below.
list1 = ['a','b','c']
list2 = ['d','e','f']
list3 = [1,2,3]
output expected
ad1
be2
cf3
Can anyone help me with this??
You can do this with map function as well, but if with loop, here's your answer. We have to concatenate the first elements of all three list, second with second and third with third. So make a loop going from zero to len(<any_list>) [because all three list have same len] and concatenate all three. Your code:
list1=["a","b","c"]
list2=["d","e","f"]
list3=[1,2,3]
list4=[]
for i in range(0,len(list1)):
list4. append (list1[i]+list2[i]+str(list3[i]))
print(*list4)
Nested loops do not achieve parallel iteration of multiple iterables. They are suited when you want to pair every element from one iterable with ervery element from another ("Cartesian product"). For parallel (pair/tuple-wise) iteration, use zip:
for x in zip(list1, list2, list3):
print("".join(map(str, x)))
# ad1
# be2
# cf3
Some documentation:
map
zip
str.join
str

I need to convert the given list of String format to a single list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str+=str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
Used for loop to read the content in list a.
Then again used a for loop to read each character in the string of i.
Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
Then appended the nums_str to the list a1 if j if = "," or "]".
Continued the above process on each item in a.
After the for loop gets over, i change a to copy of a1.
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']

How to autodefine elements from a list in Python 2.7? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to create a list of both strings and integers, and make the strings work as variables whose value is the integers number.
list = ("y","1","x","3")
str(list[0]) == int(list[1])
str(list[2]) == int(list[3])
z = x + y
print(z)
I tried this, but it does't work anyway. Anybody knows a possible solution for that?
Use a dictionary:
data = {"y": 1, "x": 3}
z = data["y"] + data["x"]
print(z) # 4
Also:
list = ("x", "1", "y", "3")
Does not create a list, that creates a tuple. Also, don't use names like list as it is using the same name as the built-in list.
In [1]: exec 'y=1+1'
In [2]: y
Out[2]: 2
Needless to say that a dictionary is way better and that you should not trust user-provided input, personally I highly discourage you to pursue this path.
You can use zip() function to get the pairs and then use exec() to assign the integers to names:
>>> items = ("y","1","x","3")
>>> for i,j in zip(items[0::2], items[1::2]):
... exec("{}={}".format(i,j))
...
>>> x+y
4
But note that you need to be sure about the identity of your items, because using exec() might harm your machine.
Or as a more pythonic approach you can use a dict:
>>> items = ("y","1","x","3")
>>> the_dict = {i:int(j) for i, j in zip(items[0::2], items[1::2])}
>>>
>>> the_dict['x'] + the_dict['y']
4
Again in this case you need be sure of the type of items because converting the digits might raise an exception if they are not valid digits.

reversed() vs. xrange() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to traverse a list backwards. I read about xrange() and reversed(). Which one is more expensive?
You can use Python's timeit library to time things like this. You don't say what kind of list you have, so I am assuming a simple list of strings. First I create a list 100 items long and then time both:
my_list = ["hello"] * 100
def v1():
for x in my_list[::-1]:
pass
def v2():
for x in reversed(my_list):
pass
print timeit.timeit(v1)
print timeit.timeit(v2)
This gives the following result:
2.78170533583
2.13084949985
As you can see, in this example reversed() is a bit faster.
xrange() produces a sequence of numbers. You can then use those numbers as list indices if you want, or you can use them for anything where you want those numbers.
for i in xrange( len(l)-1, -1, -1):
item = l[i]
print item
reversed() produces the items from something that has a length and can be indexed.
for item in reversed(l):
print item
I would use reversed() because it makes you code shorter, simpler, clearer, and easier to write correctly.

element that appear more that once in the list in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Please help (I know that it's a silly question):
I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?
To exclude items from the list that appear more than once:
d = [x for x in d if d.count(x) == 1]
For the example provided above, d will bind to an empty list.
Others have posted good solutions to remove duplicates.
Convert to a set then back again:
list(set(d))
If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated:
[x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]
Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available:
a = []
for x in d:
if x not in a:
a.append(x)
Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element.
Lets say you got a list named Words and a list UniqueWords, start a loop on Words, on each iteration you check if the list UniqueWords contains the iterated element, if so then continue, if not then add it to the UniqueWords. In the end you will have a list without duplicates. Another way you could do is a loop in a loop and instead of adding you'd remove it if it was found more than once :)
I bet there are far more efficient ways though.
If you're not worried about the order, d = list(set(d))).
If order matters check out the unique_everseen function in the itertools recpies documentation. It give a relatively clean iterator-based solution.
If order doesn't matter, convert to a set.
If you shouldn't have done that already, make sure to read the python docs on itertools, especially product(), permutations() and combinations().

Categories