I want to select multiple groups of three or more elements from a list, according to some indices.
I thought of using itemgetter, but it does not work for multiple sets, for example
labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a[0])(labels))
where
a=[(1, 2, 7), (1, 2, 8)]
works well, whereas
labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a)(labels))
gives the error
list indices must be integers or slices, not list
Is there a way to pass multiple sets of indices to itemgetter, or is there some other convenient alternative?
You are trying to parse several indexes, as stated. To make it easier you can use numpy.
labels = np.array(['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15'])
print([list(labels[index_tuples])] for index_tuples in a)
What this is doing is getting multiple sets of indexes using your tuples and printing them as a list.
Source: Access multiple elements of list knowing their index
Related
Say I have in python a list of tuples
list1 = [(1,1,1), (2,2,2), (3,3,3)]
If I want to separate them into a list of all the 1 position values, 2 position values and 3 position values I would do:
ones = [tuple[0] for tuple in list1]
twos = [tuple[1] for tuple in list1]
threes = [tuple[2] for tuple in list1]
This sort of way can become very cumbersome the more elements each tuple in that list will have. Is there a cleaner way to do this possibly using the zip method or a reverse of it?
You can use zip for this:
list(zip(*list1))
output:
[(1, 2, 3), (1, 2, 3), (1, 2, 3)]
As #paoloaq noted, you can unpack these into separate lists:
ones, two, threes = list(zip(*list1))
or if you want lists instead of tuples:
ones, two, threes = map(list, list(zip(*list1)))
Sidenote: try avoiding variable names like list and tuple.
I am looking for a method to generate all possible combinations of a list of lists, under the condition that there should only be "elementwise" combinations. Thus, if we have the lists [1,2] and [3,4], then the outcome [3,2] is allowed, but [4,2] is not allowed. With itertools.product(*lists) the last outcome is included.
Thus, I want the following output: [1,2], [3,2], [1,4], [3,4], and the following options should be 'skipped': [4,2], [1,3]. Note that the order is important! Thus I do not allow [2,3], just [3,2].
I know that I can check for this afterwards, but since I am generating many many lists in my code, I rather avoid this.
You could store the two lists in one list of lists and then after transposing the container list, use itertools.product() on it.
import itertools
original_list = [[1,2], [3,4]]
transposed_list = list(map(list, zip(*original_list)))
print(list(itertools.product(*transposed_list)))
Outputs:
[(1, 2), (1, 4), (3, 2), (3, 4)]
EDIT | Explaining how the list was transposed:
By definition, transposing is the process of exchanging places.
*original_list means [1,2] and [3,4]. The asterisk refers to the elements of the list, rather than the list as a whole
zip basically pairs values together 'element-wise':
e.g. with our original_list we have [1,2] and [3,4]. Calling zip on our elements will result in (1,3) and (2,4). The values were paired element-wise.
Note that the resulting pairs are not in list form.
map applies a function to every element in an input list. In our example,
we want to apply the (built-in) list function to our element-wise pairs - i.e. convert each tuple of pairs into a list. This is what turns (1,3) and (2,4) into [1,3] and [2,4]
Finally, convert our result from the mapping into a containing list, holding our element-wise pairs, producing [ [1,3], [2,4] ]
I'm working with lists that could have "ambiguous" values in certain places. The lists are small enough that implementing backtracking search seems silly. Currently, I'm representing ambiguous values in my lists with sub-lists containing possible values. For instance, the list:
[1, 2, [3,4]]
Could be either the list [1,2,3] or [1,2,4]. Lists may have multiple ambiguous values in them, though ambiguous elements may not themselves contain ambiguous elements. Given a list with ambiguous values in it, I'm trying to generate a list of all the possible lists that list could represent. The previous list should return [[1,2,3],[1,2,4]].
Is there an elegant way to do this? I tried to recursively build each list backwards and append to an empty list, but I can't quite wrap my brain around how to do it.
You can use itertools.product, but you'll have to modify your source list slightly:
>>> import itertools
>>> l = [[1], [2], [3, 4]]
>>> list(itertools.product(*l))
[(1, 2, 3), (1, 2, 4)]
I'm trying to sort the rows of one array by the values of another. For example:
import numpy as np
arr1 = np.random.normal(1, 1, 80)
arr2 = np.random.normal(1,1, (80,100))
I want to sort arr1 in descending order, and to have the current relationship between arr1 and arr2 to be maintained (ie, after sorting both, the rows of arr1[0] and arr2[0, :] are the same).
Use argsort as follows:
arr1inds = arr1.argsort()
sorted_arr1 = arr1[arr1inds[::-1]]
sorted_arr2 = arr2[arr1inds[::-1]]
This example sorts in descending order.
Use the zip function: zip( *sorted( zip(arr1, arr2) ) ) This will do what you need.
Now the explanation:
zip(arr1, arr2) will combine the two lists, so you've got [(0, [...list 0...]), (1, [...list 1...]), ...]
Next we run sorted(...), which by default sorts based on the first field in the tuple.
Then we run zip(...) again, which takes the tuples from sorted, and creates two lists, from the first element in the tuple (from arr1) and the second element (from arr2).
I'm following a couple of Pythone exercises and I'm stumped at this one.
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
# +++your code here+++
return
What is a Tuple? Do they mean a List of Lists?
The tuple is the simplest of Python's sequence types. You can think about it as an immutable (read-only) list:
>>> t = (1, 2, 3)
>>> print t[0]
1
>>> t[0] = 2
TypeError: tuple object does not support item assignment
Tuples can be turned into new lists by just passing them to list() (like any iterable), and any iterable can be turned into a new tuple by passing it to tuple():
>>> list(t)
[1, 2, 3]
>>> tuple(["hello", []])
("hello", [])
Hope this helps. Also see what the tutorial has to say about tuples.
Why are there separate tuple and list data types? (Python FAQ)
Python Tuples are Not Just Constant Lists
Understanding tuples vs. lists in Python
A tuple and a list is very similar. The main difference (as a user) is that a tuple is immutable (can't be modified)
In your example:
[(2, 2), (1, 3), (3, 4, 5), (1, 7)]
This is a list of tuples
[...] is the list
(2,2) is a tuple
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −
tup1 = ('Dog', 'Cat', 2222, 555555);
tup2 = (10, 20, 30, 40, 50 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (45,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
The best summary of the differences between lists and tuples I have read is this:
One common summary of these more interesting, if subtle, differences is that tuples are heterogeneous and lists are homogeneous. In other words: Tuples (generally) are sequences of different kinds of stuff, and you deal with the tuple as a coherent unit. Lists (generally) are sequences of the same kind of stuff, and you deal with the items individually.
From: http://news.e-scribe.com/397
Tuples are used to group related variables together. It's often more convenient to use a tuple rather than writing yet another single-use class. Granted, accessing their content by index is more obscure than a named member variable, but it's always possible to use 'tuple unpacking':
def returnTuple(a, b):
return (a, b)
a, b = returnTuple(1, 2)
In Python programming, a tuple is similar to a list. The difference between them is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
data-types-in-python