Ich denke, das kann tun, was Sie wollen:
>>> def two_dim(inval, width=5):
... out = []
... for i in range(0, len(inval) - 1, width):
... out.append(list(inval[i:i + width]))
... return out
...
>>> print(two_dim('mannysattynastysillyfully'))
[['m', 'a', 'n', 'n', 'y'], ['s', 'a', 't', 't', 'y'], ['n', 'a', 's', 't', 'y'], ['s', 'i', 'l', 'l', 'y'], ['f', 'u', 'l', 'l', 'y']]
Und es zu drucken, wie Sie in der Frage:
>>> c = two_dim('mannysattynastysillyfully')
>>> for sub in c:
... print " ".join(sub)
...
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y
HINWEIS Dies wird nur erstellen komplette Reihen, so eine Breite verwenden, das nicht ein Faktor der Länge der Eingabekette führt in verlorenen Daten. Das ist leicht zu ändern, wenn es gewünscht wird, aber ich werde das dem Leser als Übung überlassen.
Wenn Sie schauen, um immer einen Platz 2x2 zu schaffen, dann könnte man so etwas wie
def is_square(l):
return math.floor(math.sqrt(l))**2 == l
def two_dim_square(inval):
if not is_square(len(inval)):
raise Exception("string length is not a perfect square")
width = math.sqrt(len(inval))
# proceed like before with a derived width
EDIT 2
def two_dim(inval, width=5):
out = []
for i in range(0, len(inval) - 1, width):
out.append(list(inval[i:i + width]))
return out
def print_array(label, inval, joiner=' '):
print label
for sub in inval:
print joiner.join(sub)
print
print_array("3 by X", two_dim('mannysattynastysillyfully', 3))
print_array("4 by X", two_dim('mannysattynastysillyfully', 4))
print_array("5 by X", two_dim('mannysattynastysillyfully', 5))
print_array("6 by X", two_dim('mannysattynastysillyfully', 6))
Gibt dem Ausgang
3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l
4 by X
m a n n
y s a t
t y n a
s t y s
i l l y
f u l l
5 by X
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y
6 by X
m a n n y s
a t t y n a
s t y s i l
l y f u l l
tun EDIT 3
Wenn Sie alle Daten wollen immer vorhanden sein, und einen Standardwert für leere Zellen verwenden, dann sieht das wäre wie
def two_dim(inval, width=5, fill=' '):
out = []
# This just right-pads the input string with the correct number of fill values so the N*M is complete.
inval = inval + (fill * (width - (len(inval) % width)))
for i in range(0, len(inval) - 1, width):
out.append(list(inval[i:i + width]))
return out
Called mit
print_array("3 by X", two_dim('mannysattynastysillyfully', 3, '*'))
OUTPUT
3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l
y * *
Was genau meinen Sie mit 'dynamic array'? – Thomas
@Thomas bedeutet, dass die Array-Größe sich nach der Benutzerzeichenfolge richtet zB wenn der String 25chr lang ist, würde das Array die Größe 5x5 haben. –
Es gibt wirklich kein natives mehrdimensionales Array in Python. Es gibt ein paar Bibliotheken, die dies tun können, einschließlich Pandas und Tablib. Sie können auch eine Liste von Listen oder etwas ähnliches verwenden. –