Как я могу найти местоположения объекта в списке Python списков?

Как обсуждалось в ссылке @ TomNash, проблема заключается в большом np.matrix.

ndarray и sparse матрица работает нормально:

In [309]: slg.expm(np.ones((200,200)));                                         
In [310]: slg.expm(sparse.csc_matrix(np.ones((200,200))));                      
In [311]: slg.expm(np.matrix(np.ones((200,200))));  
ValueError: shapes (200,200) and (1,200) not aligned: 200 (dim 1) != 1 (dim 0)

Не каждый np.matrix создает проблемы:

In [313]: slg.expm(np.matrix(np.eye(200)));

Превращение np.matrix обратно в ndarray работает:

In [315]: slg.expm(np.matrix(np.ones((200,200))).A);

Здесь используется slg.matfuncs._expm(A, use_exact_onenorm='auto')

, который имеет тест, в начале, для:

if use_exact_onenorm == "auto":
    # Hardcode a matrix order threshold for exact vs. estimated one-norms.
    use_exact_onenorm = A.shape[0] < 200

Это частично объясняет, почему мы получаем проблема с (200 200) матрицей, но не с (199 199).

Это работает:

slg.matfuncs._expm(M, use_exact_onenorm=True);

Не удается с False. Но оттуда я теряюсь в деталях того, как он устанавливает _ExpmPadeHelper и пытается Pade order 3.

Короче - избегайте np.matrix, особенно если (200,200) или больше.

5
задан 13 May 2009 в 07:19
поделиться

9 ответов

It looks likes you want, for a list of sublists and a given item, to return a list of pairs where each pair is (the index of the sublist, the index of the item within the sublist). You can do that using list comprehensions and Python's built in enumerate() function:

def getPosition(list, item):
    return [(i, sublist.index(item)) for i, sublist in enumerate(list)]

Edit: See @scribble's answer above/below.

5
ответ дан 18 December 2019 в 08:31
поделиться

Если вам нужно что-то, что одновременно

  • найдет дубликаты и
  • обработает вложенные списки (списки списков списков ...)

, вы можете сделать что-то вроде следующего :

def get_positions(xs, item):
    if isinstance(xs, list):
        for i, it in enumerate(xs):
            for pos in get_positions(it, item):
                yield (i,) + pos
    elif xs == item:
        yield ()

Тестирование:

>>> xs = [['1', '2', '4', '6'],
...       ['7', '0', '1', '4'],
...       [ [ '0', '1', '1'], ['1']]
...       ]
>>> print list(get_positions(xs, '1'))
[(0, 0), (1, 2), (2, 0, 1), (2, 0, 2), (2, 1, 0)]
7
ответ дан 18 December 2019 в 08:31
поделиться
def getPosition(list, item):
    return [(i, sublist.index(item)) for i, sublist in enumerate(list) 
                                                      if item in sublist]
3
ответ дан 18 December 2019 в 08:31
поделиться
def get_positions(xs, target):
    return [(i,e.index(target)) for i,e in enumerate(xs)]

That's a good starting point. Presumably you have some sort of class such as

class SomeClass:
    def __init__(self):
        self.xs = [['1','2','4','6'], ['7','0','1','4']]

    def get_positions(self, target):
        return [(i,e.index(target)) for i,e in enumerate(self.xs)]

which in this case would let you say

model = SomeClass()
model.get_position(1)    # returns [(0,0), (1,2)]

Note that in both cases you'll get an exception if your target isn't in every one of your sublists. The question does not specify whether this is the desired behavior.

2
ответ дан 18 December 2019 в 08:31
поделиться

Если вам не нужно исключение, если элемент отсутствует в списке, попробуйте это. Также в качестве генератора, потому что они классные и универсальные.

xs = [['1', '2', '4', '6'], ['7', '0', '1', '4']]
def get_positions(xs, item):
    for i, xt in enumerate( xs ):
        try: # trying beats checking
            yield (i, xt.index(item))
        except ValueError: 
            pass

print list(get_positions(xs, '1'))
print list(get_positions(xs, '6'))

# Edit for fun: The one-line version, without try:

get_positions2 = lambda xs,item: ((i,xt.index(item)) for  i, xt in enumerate(xs) if item in xt)

print list(get_positions2(xs, '1'))
print list(get_positions2(xs, '6'))
2
ответ дан 18 December 2019 в 08:31
поделиться

A while ago I wrote a library for python to do list matching that would fit the bill pretty well. It used the tokens ?, +, and * as wildcards, where ? signifies a single atom, + is a non-greedy one-or-more, and * is greedy one-or-more. For example:

from matching import match

match(['?', 2, 3, '*'], [1, 2, 3, 4, 5])
=> [1, [4, 5]]

match([1, 2, 3], [1, 2, 4])
=> MatchError: broken at 4

match([1, [2, 3, '*']], [1, [2, 3, 4]])
=> [[4]]

match([1, [2, 3, '*']], [1, [2, 3, 4]], True)
=> [1, 2, 3, [4]]

Download it here: http://www.artfulcode.net/wp-content/uploads/2008/12/matching.zip

0
ответ дан 18 December 2019 в 08:31
поделиться

Вот версия без try..except, возвращающая итератор, а для

[['1', '1', '1', '1'], ['7', '0', '4']]

возвращается

[(0, 0), (0, 1), (0, 2), (0, 3)] 


def getPosition1(l, val):
  for row_nb, r in enumerate(l):
      for col_nb in (x for x in xrange(len(r)) if r[x] == val):
         yield row_nb, col_nb
0
ответ дан 18 December 2019 в 08:31
поделиться

Самый сложный и, вероятно, самый медленный способ сделать это:

    >>> value = '1'
    >>> l = [['1', '2', '3', '4'], ['3', '4', '5', '1']]
    >>> m = []
    >>> for i in range(len(l)):
    ...  for j in range(len(l[i])):
    ...   if l[i][j] == value:
    ...    m.append((i,j))
    ...
    >>> m
    [(0, 0), (1, 3)]
0
ответ дан 18 December 2019 в 08:31
поделиться

Here is another straight forward method that doesn't use generators.

def getPosition(lists,item):
    positions = []
    for i,li in enumerate(lists):
        j = -1
        try:
            while True:
                j = li.index(item,j+1)
                positions.append((i,j))
        except ValueError:
            pass
    return positions

l = [['1', '2', '4', '6'], ['7', '0', '1', '4']]
getPosition(l,'1')  #returns [(0, 0), (1, 2)]
getPosition(l,'9') # returns []

l = [['1', '1', '1', '1'], ['7', '0', '1', '4']]
getPosition(l,'1')  #returns [(0, 0), (0, 1), (0,2), (0,3), (1,2)]
0
ответ дан 18 December 2019 в 08:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: