sorting list of lists Python 2.7 - python

To remove duplicates in list of lists (named 'povijest'), I used:
povijest=[ list(set(x)) for x in povijest ]
But I makes some structure problem when printed because its not sorted.
Whats the syntax when sorting lists in list of lists?

This will sort by the first element in each list
povijest= sorted([list(set(x)) for x in povijest ])
This will sort each sub-list, then sort the whole thing by the first element
povijest = sorted([sorted(i) for i in provijest])
Input
proviject = [['a','c','b'],['z','y','x'],['e','a']]
Result
[['a', 'b', 'c'], ['a', 'e'], ['x', 'y', 'z']]

Related

How to Check if Element exists in Second Sublist?

If I had a list like this:
L = [
['a', 'b'],
['c', 'f'],
['d', 'e']
]
I know that I could check if e.g. 'f' was contained in any of the sub lists by using any in the following way:
if any('f' in sublist for sublist in L) # True
But how would I go about searching through second sub lists, i.e. if the list was initialized the following way:
L = [
[
['a', 'b'],
['c', 'f'],
['d', 'e']
],
[
['z', 'i', 'l'],
['k']
]
]
I tried chaining the for in expressions like this:
if any('f' in second_sublist for second_sublist in sublist for sublist in L)
However, this crashes because name 'sublist' is not defined.
First write your logic as a regular for loop:
for first_sub in L:
for second_sub in first_sub:
if 'f' in second_sub:
print('Match!')
break
Then rewrite as a generator expression with the for statements in the same order:
any('f' in second_sub for first_sub in L for second_sub in first_sub)
If you don't need to know where 'f' is located you can leverage itertools here as well.
import itertools
any('f' in x for x in itertools.chain.from_iterable(l))
This will flatten your nested lists and evaluate each list separately. The benefit here is if you have three nested lists this solution would still function without having to continue writing nest for loops.

How to insert elements in a nested List in Python? [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 4 years ago.
I do not have much experience in Python.
All I want to do is to insert elements in nested lists.I have two lists which seems to be similar but their behaviour is completely different.
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
When I output print these two lists both give same output:
[['a', 'b'], ['a', 'b'], ['a', 'b']]
But when I try to insert elements in nested lists both do that in a different way. Below is the code for inserting elements in nested list.
list1 = [['a','b']] * 3
for item in list1:
item.append("Hello")
print (list1)
This outputs
[['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello']]
While when I define list in the following way it does exactly what I want.
list2 = [['a','b'],['a','b'],['a','b']]
for item in list2:
item.append("Hello")
print (list2)
This gives following output:
[['a', 'b', 'Hello'], ['a', 'b', 'Hello'], ['a', 'b', 'Hello']].
Why are these two behaving differently?
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
Screenshot of Program output
list1 = [['a', 'b']] * 3
This creates a list of lists, as you know. However, the nested lists are actually all references to the same list object.
So when you iterate over list1 with
for item in list1:
item refers to the same list object on each iteration. So you repeated append to the same list.
On the other hand, list2 in your example code is explicitly assigned a list with three different lists. Those lists happen to have the same elements, but they are distinct lists.
When you use the * operator here, you are saying "I want 3 of these".
So you're getting 3 references to the same ['a', 'b']. In your case, you're adding 'Hello' to that same ['a', 'b'] reference.
List of lists changes reflected across sublists unexpectedly
If you want to make 3 separate references, try using list comprehension:
>>> x = [['a', 'b'] for i in range(0, 3)]
>>> x
[['a', 'b'], ['a', 'b'], ['a', 'b']]
>>> x[0].append('Hello')
>>> x
[['a', 'b', 'Hello'], ['a', 'b'], ['a', 'b']]

How to copy list of lists from python without last elements from each list [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 5 months ago.
How can I copy list of lists and delete last element from each in one step ? I can do something like this, but would like to learn to do it in one step:
test2 = [["A","A","C"],
["C","A"],
["A","B","C","A"]]
import copy
test3 = copy.deepcopy(test2)
for item in test3:
del item[-1]
In one step, you'll want to use a list comprehension. Assuming your lists are two dimensional only and the sublists composed of scalars, you can use the slicing syntax to create a copy.
>>> [x[:-1] for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]
If your sublists contain mutable/custom objects, call copy.deepcopy inside the expression.
>>> [copy.deepcopy(x[:-1]) for x in test2]
[['A', 'A'], ['C'], ['A', 'B', 'C']]

Python - binary search in sorted list of lists

Is it a way in Python 3 to binary search in sorted list of lists?
Let's assume I have a list of lists:
list = [['A', 'B', 3], ['C', 'D', 1], ['E', 'F', 2]]
I've sorted it by 3d element in inner list with:
list = sorted(list , key=itemgetter(2))
and now list is
[['C', 'D', 1], ['E', 'F', 2], ['A', 'B', 3]]
And now how can I search in this sorted list with binary search (O(log(n)) time complexity) using element from inner list by which sorting was done?
Like
findBy(list, index_of_inner_list, value_of_inner_list_to_find)
Outer list is huge. Inner lists have len 50. And I need to make many queries to extract some elements from outer list based on condition related to inner lists. I was thinking about bisect but inner arrays would be a problem for it I think.

zip the values from a dictionary [duplicate]

This question already has an answer here:
zip two values from the dictionary in Python
(1 answer)
Closed 6 years ago.
I have a dictionary in python 2.7 that has the following structure:
x = {
'1': ['a', 'b', 'c'],
'2': ['d', 'e', 'f']
}
The length of the value list is always the same and I would like to basically zip the value lists with corresponding values. So, in this case it will create three new lists as:
[['a', 'd'], ['b', 'e'], ['c', 'f']]
I know I can write an awful looking loop to do this but I was wondering if there is a more pythonic way to do this. I need to preserve the order.
You can do the following:
zip(*x.values())
Explanation:
x.values() returns [['a', 'b', 'c'], ['d', 'e', 'f']] (order may change so you might need to sort x first.)
zip([a, b], [c, d]) returns [[a, c], [b, d]]
To expand x.values() into arguments to zip, prepend * to it.
This is single line solves the problem but is likely worse looking than your loop. It loops over the sorted keys and produces a list to pass to zip and then maps over the result converting the tuples into lists.
>>> x = {'1': ['a', 'b', 'c'], '2': ['d', 'e', 'f']}
>>> map(list, zip(*[x[k] for k in sorted(x)]))
[['a', 'd'], ['b', 'e'], ['c', 'f']]
res = list(zip(x['1'], x['2']))
res = list(map(list, res))
An explanation:
zip(x['1'], x['2'])
Creates a zip object that links up your pairs.
res = list(zip(x['1'], x['2']))
That zip object now become a list of tuples.
list(map(list, res))
For each element in res (each tuple), change the data structure from tuple to list, as you requested in your desired output above (map the list data type onto all elements in res). Then, convert that map object into a list to arrive at the final, desired result.

Categories

Resources