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 5 years ago.
Improve this question
new here and somewhat new to Python. I am having a blank and would appreciate some guidance.
I am trying to write a nested list, then write a for loop to print a comma seperated list of the numbers using like indicies from each list to pair-up the numbers. I have my code below(2.7.14):
FirstNumbers = [1, 2, 3]
SecondNumbers = [4, 5, 6]
ThirdNumbers = [7, 8, 9]
NestedNumbers = [FirstNumbers, SecondNumbers, ThirdNumbers]
for i in range(0, 3):
for each_number in NestedNumbers:
print each_number[i],
#Output
1 4 7 2 5 8 3 6 9
My current issue is trying to get the numbers to read [1, 4, 7] and so on. I would appreciate any guidance.
Thank you
I think you need empty list so you can append the numbers to that i.e
FirstNumbers = [1, 2, 3]
SecondNumbers = [4, 5, 6]
ThirdNumbers = [7, 8, 9]
NestedNumbers = [FirstNumbers, SecondNumbers, ThirdNumbers]
m = []
for i in range(0, 3):
k = []
for each_number in NestedNumbers:
k.append(each_number[i])
m.append(k)
Output m : [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
You need to put "print "[" after "for i in range(0,3)" and a print "]" after the "for each_number" part
so that it will print:
[1 4 7][2 5 8][3 6 9]
Now you need to insert a print ", " before "print each_number[i]"
You will end up with:
[, 1, 4, 7][, 2, 5, 8][, 3, 6, 9] You need to not use print ", " on the first run-through as that is printing the comma before the first number.
You will need to change the second for statement to not go through "NestedNumbers" because you cannot know if it is the first one, but instead "range(0,len(NestedNumbers))" so that you can check to see if it is the first iteration and whether you need to add a comma.
change it to:
FirstNumbers = [1, 2, 3]
SecondNumbers = [4, 5, 6]
ThirdNumbers = [7, 8, 9]
NestedNumbers = [FirstNumbers, SecondNumbers, ThirdNumbers]
for x in range(0,3):
print "["
for y in range(0,len(NestedNumbers)):
if y!=0: print ", "
print NestedNumbers[y][i]
print "]"
Now it will print:
[1, 4, 7][2, 5, 8][3, 6, 9]
Try this
import itertools
for n in itertools.chain(*zip(FirstNumbers,SecondNumbers,ThirdNumbers))
print n,
The call to zip combines the lists as you want as a list of tuples. Then itertools.chain flattens this to a single list.
if you actually want this output:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Just print the result of calling zip
Related
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 4 months ago.
Improve this question
Suppose I have a python list as: points_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,1]
And I need to split this list containing the number of elements in the index_list=[2, 2, 6, 3] But having common endpoints
That is:
First 2 elements from points_list : [1,2]
Next 2 elements from the points_list but it should start from the place it stopped before : [2,3]
Then the next 6 elements : [3,4,5,6,7,8]
Finally, 3 elements in the same way : [8,9,1]
Ultimately, what I expect is to have something like: [[1,2],[2,3],[3,4,5,6,7,8],[8,9,1]] which corresponds to the number of elements mentioned in the index_list=[2, 2, 6, 3]
Can you please help me to perform this task
Here's my code:
points_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,1]
index_list=[2, 2, 6, 3]
res = []
end_point = 0
for i in index_list:
temp_list = points_list[end_point:end_point+i] # Get the list
res.append(temp_list) # Append it
end_point = points_list.index(temp_list[-1]) # Get the index of the last value
print(res)
Support for repeating numbers (thanks to azro and S.B):
points_list = [3, 2, 3, 4, 5, 6, 2, 8, 9, 1]
index_list=[2, 2, 6, 3]
res = []
for i in index_list:
res.append(points_list[:i]) # Append it
points_list = points_list[i-1:] # Reconfigure list
print(res)
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
So I'm trying to find the items that went in and went out of a list before and after it changed
For example, at first my list is:
[1, 1, 2, 5, 7, 7]
And then a minute later it's:
[1, 2, 2, 5, 6, 7, 4]
How would I end up with 2 lists that show what items went out and which went in like so,
itemsOut = [1,7]
itemsIn = [2, 6, 4]
Position and length can change
You can use Counter from the built-in collections module:
>>> list1 = [1, 1, 2, 5, 7, 7]
>>> list2 = [1, 2, 2, 5, 6, 7, 4]
>>> from collections import Counter
>>> counter1 = Counter(list1)
>>> counter2 = Counter(list2)
>>> l_diff = counter1-counter2
>>> r_diff = counter2-counter1
>>> print(list(l_diff))
[1, 7]
>>> print(list(r_diff))
[2, 6, 4]
You could use something like this, to detect wich items changed.
old_arr = [1, 2, 2, 5, 7, 7]
new_arr = [1, 1, 2, 5, 7, 7]
items_out = []
for element in old_arr:
if new_arr.count(element) > 0:
new_arr.pop(new_arr.index(element))
else:
items_out.append(element)
print("Items out:", items_out)
print("Items in:", new_arr)
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 2 years ago.
Improve this question
I want to find intersection of two lists with original order. So if
a = [2, 3, 5, 6]
b = [17, 28, 2, 8, 0, 3]
I need [2, 3]. But for [3, 2, 5, 6] and [17, 28, 2, 8, 0, 3] I need [2].
How I can get it?
def inter(a,b):
c = []
for num in a:
if num in b and (not len(c) or b.index(c[-1]) < b.index(num)):
c.append(num)
return c
You will have to loop over one list, searching the element in the other list, and only search the other list from that point for any following element.
Code could be:
a = [3, 2, 5, 6]
b = [17, 28, 2, 8, 0, 3]
def intersect(a,b):
result = []
ix = 0
for x in a:
try:
ix = b[ix:].index(x)
result.append(x)
except ValueError:
pass
return result
print(intersect(a, b))
It gives:
[3]
NB: if you want [2], just use intersect(b, a)
This is more of a research problem than a StackOverflow question...
The phrase to search for is "longest common subsequence problem". Once you've found an algorithm that suits your situation, it will probably be clearer how to translate it into Python, or you can ask more targeted questions here.
a = [7, 8, 6, 6, 8, 10, 3, 3]
b = [7, 4, 10, 8, 7]
def magic(a, b):
result = []
# early abort
if len(a) == 0 or len(b) == 0:
return result
try:
index_b = b.index(a[0])
result.append(b[index_b])
# a[0] was found in b at index index_b. Disregard any items before index_b in the future.
# And since we found a[0], we can remove it from our search list a.
# continue with next search
return result + magic(a[1:], b[index_b+1:])
except ValueError:
# a[0] is not in b. continue with next item in a.
# No need for new code, just do the same function again for a shorter a.
return result + magic(a[1:], b)
print(magic(a,b))
This prints [7,8]. I hope the code is self-explanatory.
It fulfills your test case 1:
a = [2, 3, 5, 6]
b = [17, 28, 2, 8, 0, 3]
# prints [2, 3]
It does not fulfill your test case 2:
>>> a = [3, 2, 5, 6]
>>> b = [17, 28, 2, 8, 0, 3]
>>> tmp.magic(a,b)
[3]
# you wanted [2]
But it does follow my earlier comment (to which you said "YES")
#jevik So what you want to do is to take a[0] iff it is in b, then take a[1] iff it is in b after the index where a[0] was in b and so on? – lucidbrot 41 mins ago
Your test case 3 from a comment:
For a=7 8 6 6 8 10 3 3 and b=7 4 10 8 7 with your solve I get 7 8 10. I need to get 7 8
My program does print [7,8] for that.
You can use & operation between two sets, that will give you an intersection set without change in order
a = [2, 3, 5, 6]
b = [17, 28, 2, 8, 0, 3]
intersection = list(set(a) & set(b))
print(intersection)
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 3 years ago.
Improve this question
I want to replace variables in a list with combination of elements.
To be more specific:
I have these two lists
liste1 = [1,2,3,'X','X',4]
liste2 = [5,6,7]
and I want to get a list containing the elements below :
[1,2,3,5,6,4]
[1,2,3,5,7,4]
[1,2,3,6,7,4]
[1,2,3,6,5,4]
[1,2,3,7,5,4]
[1,2,3,7,6,4]
Does anyone have an idea how to make it ?
You can do it this way:
from itertools import permutations
liste1 = [1, 2, 3, 'X', 'X', 4]
liste2 = [5, 6, 7]
def replacements(liste1, liste2):
x_indices = [i for i, val in enumerate(liste1) if val == 'X']
nb = len(x_indices)
for perm in permutations(liste2, nb):
l1 = liste1[:] # if we want to preserve the original and yield different lists
for i, new_val in zip(x_indices, perm):
l1[i] = new_val
yield l1
for r in replacements(liste1, liste2):
print(r)
Output:
[1, 2, 3, 5, 6, 4]
[1, 2, 3, 5, 7, 4]
[1, 2, 3, 6, 5, 4]
[1, 2, 3, 6, 7, 4]
[1, 2, 3, 7, 5, 4]
[1, 2, 3, 7, 6, 4]
We first list the indices where 'X' appears, then generate the permutations of as many elements of liste2. For each permutation, we replace the 'X's.
This question already has answers here:
(Python) adding a list to another without the brackets
(3 answers)
Closed 7 years ago.
Here I'm trying to merge this two lists, making one whit all items.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(n):
s=[]
for x in n:
s.append(x)
return s
print flatten(n)
I'm trying to have as a result
[1,2,3,4,5,6,7,8,9]
but I'm getting
[[1, 2, 3], [4, 5, 6, 7, 8, 9]]
I dont understand why, I think I'm clearly assigning each value to the list 's' in the for loop.
You're appending to the list. Each sublist is appended to the new list as its own item, exactly the way it was originally. You want to extend the list instead:
s.extend(x)
Use extend, instead of append
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(n):
s=[]
for x in n:
s.extend(x)
return s
print flatten(n)
Best of luck.
You should be using list.extend, append is appending each sublist not adding just the contents. x is each sublist so just appending the sublist is obviously going to give you a list of lists again.
You can also use itertools.chain to flatten the list:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
print(list(chain.from_iterable(n)))
Or use a list comp:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
print([ele for sub in n for ele in sub])