Создание списков списков pythonic способом

Я запустил обе замены для одного и того же файла, который находится на диске Unix, и использовал путь unc к нему \ server \ path ...:

<ReplaceFileText
  InputFilename="$(fileToUpdate)"
  OutputFilename="$(fileToUpdate)"
  MatchExpression="15.0.0"
  ReplacementText="15.3.1"/>


<FileUpdate Files="$(fileToUpdate2)"
            Regex="15.0.0"
            ReplacementText="15.3.1" />

, а пользовательское действие cs выше не добавляет бомба; однако FileUpdate сделал:

%head -2 branding.h branding2.h
==> branding.h <==
#/* branding.h
#** This file captures common branding strings in a format usable by both sed and C-preprocessor.

==> branding2.h <==
#/* branding.h
#** This file captures common branding strings in a format usable by both sed and C-preprocessor.

Спасибо csharptest.net - я делал exec с командами perl subtitute для сборок unix.

11
задан Alasdair 17 April 2018 в 19:39
поделиться

8 ответов

Используйте понимание списка :

>>> mat = [[0]*2 for x in xrange(3)]
>>> mat[0][0] = 1
>>> mat
[[1, 0], [0, 0], [0, 0]]

Или как функцию:

def matrix(rows, cols):
    return [[0]*cols for x in xrange(rows)]
9
ответ дан 3 December 2019 в 01:45
поделиться

Попробуйте следующее:

>>> cols = 6
>>> rows = 3
>>> a = [[0]*cols for _ in [0]*rows]
>>> a
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> a[0][3] = 2
>>> a
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

Это также обсуждается в этом ответе :

>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]
8
ответ дан 3 December 2019 в 01:45
поделиться

Это будет работать

col = 2
row = 3
[[0] * col for row in xrange(row)]
3
ответ дан 3 December 2019 в 01:45
поделиться

Я использую

mat = [[0 for col in range(3)] for row in range(2)]

, хотя в зависимости от того, что вы делаете с матрицей после ее создания, вы можете взглянуть на использование массива NumPy.

4
ответ дан 3 December 2019 в 01:45
поделиться

Что насчет:

m, n = 2, 3
>>> A = [[0]*m for _ in range(n)]
>>> A
[[0, 0], [0, 0], [0, 0]]
>>> A[0][0] = 1
[[1, 0], [0, 0], [0, 0]]

Понимание списка; из документов :

List comprehensions provide a concise way to create lists 
without resorting to use of     
map(), filter() and/or lambda. 
The resulting list definition tends often to be clearer    
than lists built using those constructs.
2
ответ дан 3 December 2019 в 01:45
поделиться

См. Также этот вопрос для обобщения на n-уровневый вложенный список / n-мерную матрицу.

1
ответ дан 3 December 2019 в 01:45
поделиться

Этот ответ быстрее принятого!
Использование xrange (rows) вместо [0] * rows не имеет значения.

>>> from itertools import repeat
>>> rows,cols = 3,6
>>> a=[x[:] for x in repeat([0]*cols,rows)]

Вариант, который не использует itertools и работает с той же скоростью

>>> a=[x[:] for x in [[0]*cols]*rows]

Из ipython:

In [1]: from itertools import repeat

In [2]: rows=cols=10

In [3]: timeit a = [[0]*cols for _ in [0]*rows]
10000 loops, best of 3: 17.8 us per loop

In [4]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
100000 loops, best of 3: 12.7 us per loop

In [5]: rows=cols=100

In [6]: timeit a = [[0]*cols for _ in [0]*rows]
1000 loops, best of 3: 368 us per loop

In [7]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
1000 loops, best of 3: 311 us per loop
7
ответ дан 3 December 2019 в 01:45
поделиться

Есть ли что-нибудь, чего не может сделать itertools? :)

>>> from itertools import repeat,izip
>>> rows=3
>>> cols=6
>>> A=map(list,izip(*[repeat(0,rows*cols)]*cols))
>>> A
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> A[0][3] = 2
>>> A
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
1
ответ дан 3 December 2019 в 01:45
поделиться
Другие вопросы по тегам:

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