在python中创建动态数组

时间:2016-04-14 23:51:43

标签: python python-2.7 python-3.x

我有一个动态数组,我想更新用户字符串,例如, 对于25个字符的单个字符串,例如' mannysattynastysillyfully'。会有一个5x5阵列。

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

我尝试过多种方法,并通过广泛搜索获得了一些信息 1. How to define two-dimensional array in python 2. How to take input in an array + PYTHON? 3。python - how to split an input string into an array?

仍然无法理解我应该如何处理进入动态数组的用户值

1 个答案:

答案 0 :(得分: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
...
>>> 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']]

并在问题中打印出来:

>>> 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

注意这只会创建完整的行,因此使用不是输入字符串长度因子的宽度将导致数据丢失。如果需要,这很容易改变,但我会将其作为练习留给读者。

如果您希望始终创建一个2x2的正方形,那么您可以执行类似

的操作
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

编辑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))

提供输出

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

编辑3
如果您希望始终存在所有数据,并使用空单元格的默认值,那么这将看起来像

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

调用
print_array("3 by X", two_dim('mannysattynastysillyfully', 3, '*'))

<强>输出

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 * *