How to map two lists in python? [closed] - python

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

Related

Why does my nested loop append only the last thing 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 11 months ago.
Improve this question
I am working on a simple math problem that requires me to find a list of Sval values per k per w value. I have this nested for loops.
w = [0,1/3,-1]
k = [0,-1]
S = 0.001
Sval = [S]*30
Sval_list = []
for wval in w:
for kval in k:
for i in range(1, 30):
Sval[i] = Sval[i-1]+wval-kval
print("{},{}".format(wval,kval),Sval)
Sval_list.append(Sval)
The loops is expected to loop for six times, each loop would output a list of Sval. I expected an outcome of a list with shape(6,30), which I got. But it is appending the output list from 6th loop for six times, instead of appending one output list per loop. Any help to solve this question or to make my codes neater is welcomed!
At the end of the program, Sval_list contains six copies of Sval (a list), since you appended it 6 times. Each time you run through the inner most for loop and modify Sval, it modifies all copies of Sval in Sval_list since that's how lists work in python, and that's why all lists in Sval_list are the same at the end.
You can fix this by effectively detaching each Sval when you append it to Sval_list. Instead of writing Sval_list.append(Sval), write Sval_list.append(list(Sval)). The list will create a new list that no longer changes when you change Sval.
your mistake is in using the reference, by appending the Sval reference to the Sval_list.
you get a shallow copy of Sval as value and with change of Sval, all your data would be changed. appending a hard copy of Sval to the Sval_list would do the job:
Sval_list.append(Sval[:])

Check if list contains unique elements or not [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 2 years ago.
Improve this question
I want to check if a list is composed of unique elements.
For example: [1,1,1], [4,4,4,4] or [2].
List can contain any value but it must be unique throughout the list.
You can use set() to get unique elements in the list and use len() to get the count of elements in your set. If it returns length as 1, then you have only one unique element in your list:
>>> my_list = [1,1,1]
>>> len(set(my_list))
1
However above solution is not performance efficient. In case your list is huge, you should write your own function to check this efficiently as:
def is_unique(my_list):
first_elem = my_list[0]
for elem in my_list[1:]:
if elem != first_elem:
return False
return True
Test runs:
>>> is_unique([1,1,2])
False
>>> is_unique([1,1,1])
True

How to check if a list contains items from another lists sublist? [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 3 years ago.
Improve this question
I know this question has been asked several times here and I went through most of them but for some reason I am unable to utilise those solutions for my current issue.
I have a list with 11 sublists:
list_a = [[1,2,3],[2,3,4],[3,4,5].....[11,12,13]]
I also have a randomly generated list of length 9 within the range of 1 and 13:
list_b = [1,4,7,8,2,3,8,9]
I want to create a function that iterates through the sublists of list_a and returns true only if all the items within the sublist are present in list_b. I tried the 'all' function but it doesn't seem to work in my case here as it takes all the items within the list and not the sublist.
for i in list_a:
if all(a in i for a in list_b):
print ('Yes')
Thank you in advance.
You just got your all() logic twisted around. You need to check if each item in the sublist is in list_b (rather than checking if each item in list_b is in the sublist).
Change your all() logic to:
all(a in list_b for a in i)
As an aside, it would be a bit more efficient and simplify things if you changed list_b to a set.
Your thinking is right, but you are checking if elements in list_b exist in sublists of list_a, while your requirement is the inverse of it. You can use set operations here:
>>> list_a = [[1,2,3],[2,3,4],[3,4,5],[11,12,13]]
>>> list_b = [1,4,7,8,2,3,8,9]
>>> all(set(a).issubset(set(list_b)) for a in list_a)
False
or
>>> list_a = [[1,2,3],[2,3,4],[3,4,8]]
>>> all(set(a).issubset(set(list_b)) for a in list_a)
True

Test if two items in a set are found in a list element [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 7 years ago.
Improve this question
I have a set of two values called mySet. It looks something like this:
mySet = {1010101, 20202030}
And I have a list, myList, of lines that contain four strings each. A line in the list looks something like this:
1 1010101 20202030 15.3
with each of the four strings separated by a single space. I would like to construct a loop where if both of the values in mySet are contained in a single line of myList, the loop will return TRUE. I have an idea that maybe I could make a new list of just the second and third elements of each line of myList and then check the values from mySet against that, but I'm not sure how I would implement that either. Thanks in advance for your time.
If by "return" you meant a function (or any callable), you need to do so separately despite the for loop, because for loops don't return anything.
However, this problem can be easily solved with the builtin any and all functions like this:
mySet = {str(i) for i in {1010101, 20202030}}
myList = ["1 1010101 20202030 15.3"]
result = any(all(s in l for s in mySet) for l in myList)
print(result)
It will print True. We have done all of the calculation in one single line. Also, notice how I converted all the integers in to strings in the mySet - you might want to do it separately in another set, if you don't want to mutate that set.
for line in myList:
print(mySet.issubset(map(float, line.split(" "))))
split to convert space-separated values to list
map to convert all list elements to floats for comparison
issubset (or equivalently issuperset) to check whether one is a subset of the other

Part of List into String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
ok looks like many did not understand the question. i will make it more clear.
i got a list:
List_1 = [1,2,3,4,5,6,7,8,9]
and what i do in my program is that if i press 1 that will make List_1[0] into X or what ever number i press, it turns it into an X. my list has 9 numbers total.
What i want to do, is that IF 3 specific numbers are converted into X then the program will move on.
so if i end up with:
List_1 = [1,'X',3,4,'X',6,'X',8,9]
then the program will move on.
If you need a contiguous set (such as the first three entries in your original question) use slice syntax:
list_2 = a[:3]
If you need only those elements from a specific set, use a comprehension:
stuff_i_need = [1, 'gg']
list_2 = [x for x in L if x in stuff_i_need]
(although, if you know what you need and it is a very small list, then just manually accessing the locations in the list that contain the elements you need is fine).
If you want to make a string of some contents of the list, one option is to just concatenate them yourself and wrap the elements with the string constructor str:
str(L[0]) + str(L[3])
Another way to do the same thing is:
import operator
reduce(operator.add, map(str, L))
# Also, just replace L with any of the slicing or accessing mentioned above.
Use a slice, as mentioned the other answers and comments. But if the indices are non-contiguous you can use a list comprehension together with enumerate:
>>> [x for i, x in enumerate(a) if i in [0, 1, 3]]
[1, 'X', 'X']
Update
The question changed, asking instead how to take different parts of a list and join them into a string. A small modification of the above:
>>> "".join(str(x) for i, x in enumerate(L) if i in [0, 3])
'1gg'

Categories