Part of List into String [closed] - python

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'

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

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

in python: variables as indexes to slice an array doesn't work [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 6 years ago.
Improve this question
So I am trying to get a slice of an array using variables for indeces, but not working. If I hard code numbers into the indeces it all works fine. Why???
My code:
def play(startplay,stopplay):
Y = x[startplay:startplay+5]
# produces an empty list...
Y = x[1:5]
# produces the correct list
What is the value of startplay? If it's longer than the list (or negative, but close enough to 0 that startplay+5 >= 0), you'd expect to get an empty list when you slice.
>>> test = [1, 2, 3]
>>> test[-5:0] # Can't slice from negative to non-negative with implicit step of 1
[]
>>> test[-6:-1]
[1, 2]
As noted in the comments, your example is mismatched anyway; x[startplay:startplay+5] is a slice of length 5, x[1:5] is a slice of length 4.
Im with ShadowRanger on this one. I see that the operation is supposed to work and does work in the example I created below.
def trial(x1, x2):
array = [1,2,2,3,4,5,6,6,3,2,2,1,1,23,3,4,5,2,3,2,]
new_array = array[int(x1):int(x2)]
new_array2 = array[x1:x2]
print(new_array2)
print(new_array)
trial(1, 3)
[2, 2]
[2, 2]
Make sure that your list is capable of the operation first... Build up from hard examples and reference the documentation.

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