组合不同形状的阵列

时间:2018-05-13 00:29:17

标签: python python-3.x arraylist

我有2个数组,我想组合成一个数组。 第一个数组看起来像这样:

File "/home/ghostman/Projects/asknow/asknow/asknow/urls.py", line 22, in <module>
    url(r'^', include('app.urls')),
  File "/home/ghostman/Projects/asknow/env/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/ghostman/Projects/asknow/env/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/ghostman/Projects/asknow/asknow/app/urls.py", line 3, in <module>
    from app import views
  File "/home/ghostman/Projects/asknow/asknow/app/views.py", line 6, in <module>
    from app.forms import LoginForm
  File "/home/ghostman/Projects/asknow/asknow/app/forms.py", line 4, in <module>
    class LoginForm(forms.Form):
  File "/home/ghostman/Projects/asknow/asknow/app/forms.py", line 5, in LoginForm
    email = CharField(label='email', max_length=255, widget=TextInput("E-mail"))
  File "/home/ghostman/Projects/asknow/env/lib/python3.6/site-packages/django/forms/widgets.py", line 284, in __init__
    attrs = attrs.copy()
AttributeError: 'str' object has no attribute 'copy'

第二个数组如下所示:

array_a = [1,2,3,4,5]

我希望合并的结果看起来像这样:

array_b = [[2, 4, 8, 16, 32], [3, 9, 27, 81, 243], [4, 16, 64, 256, 1024],
           [5, 25, 125, 625, 3125]]

我一直在为此奋斗一天,非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

你可以用一个不太困难的列表理解来做到这一点:

In []:
[(x, z) for x, y in zip(array_a, array_b) for z in y]

Out[]:
[(1, 2), (1, 4), (1, 8), (1, 16), (1, 32), (2, 3), (2, 9), (2, 27), (2, 81),
 (2, 243), (3, 4), (3, 16), (3, 64), (3, 256), (3, 1024), (4, 5), (4, 25),
 (4, 125), (4, 625), (4, 3125)]

由于4中只有array_b个元素,5中的array_a会被忽略。

答案 1 :(得分:2)

这是一种只使用for循环

的方法
for x in range(min(len(array_a), len(array_b))):
    for b in array_b[x]:
        array_c.append([array_a[x], b])

我必须添加额外的分钟,因为第一个数组中有五个元素,第二个数组中只有四个数组

答案 2 :(得分:0)

这可能是一种更简洁的方法,但这应该有效。

array_a = [1, 2, 3, 4, 5]
array_b = [[2, 4, 8, 16, 32], [3, 9, 27, 81, 243], [4, 16, 64, 256, 1024], [5, 25, 125, 625, 3125]]

array_c = list()
for a, bs in zip(array_a, array_b):
    array_c += [[a, b] for b in bs]

print(array_c)