Python中的多维数组

时间:2016-06-19 09:19:59

标签: python

作为python中的noob我与多维数组斗争 我有这个部分

def listMembers(Members):               
    for name in Names:
        age=Ages[name]
        print (name,age)

Names = ["John","William","Sarah"] 
Ages = [22,33,44]
Members=[Names,Ages]
listMembers(Members)

期待结果:

John, 22
Willem, 33
Sarah, 44

我必须改变什么才能得到这个?

5 个答案:

答案 0 :(得分:2)

您可以使用enumerate执行任务...

def listMembers():               
        for i,name in enumerate(Names):
            age=Ages[i]
            print (name,age)

输出 -

John 22
William 33
Sarah 44

但正如评论中所说,最好在这里使用字典

另一种方法是使用zip -

def listMembers():               
    for i,j in zip(Names, Ages):
        print (i,j)

编辑:

正如评论中所述,您可以在不直接引用的情况下执行此操作,因为在现实世界中,该函数将封装在另一个类中,因此您无法直接访问数据.-

def listMembers(Members):
    names = Members[0]
    ages = Members[1]
    for i, j in zip(names, ages):
        print (i, ", ", j)

答案 1 :(得分:1)

您可以使用zip内置功能:

Names = ["John", "William", "Sarah"]
Ages = [22, 33, 44]

for name, age in zip(Names, Ages):
    print name, ',', age

答案 2 :(得分:0)

您可以使用内置函数zip()

这将为您提供元组列表。

zipped = zip(Names, Ages)
tup_list = (list(zipped))
print (tup_list)
[('John', 22), ('William', 33), ('Sarah', 44)]

您可以将tup_list变为dictionary

dict(tup_list)
{'John': 22, 'Sarah': 44, 'William': 33}

答案 3 :(得分:0)

其他答案显示了Python中很酷的内置快捷方式。但是,恕我直言,你应该首先重新访问基础知识并采取漫长的路线。

以下代码使用基本功能来创建整数列表(在您的情况下为[0,1,2]),迭代这些整数以相应地对数组进行切片。此代码假定名称和年龄具有相同数量的索引。

def listMembers(Members):
    names = Members[0] # slice off the first dimension
    ages = Members[1] # slice off the first dimension

    names_len = len(names) # get the length of names 

    for i in xrange(names_len): # xrange builds a list from 0 to given length.
        print (names[i], ages[i]) # print off the second dimension


Names = ["John","William","Sarah"]
Ages = [22,33,44]
Members=[Names,Ages]
listMembers(Members)

答案 4 :(得分:0)

这是您正在寻找的解决方案。它从Members参数中获取所需的所有信息,这可能包含任意数量的列表。列表元素被分组,转换为字符串,与", "连接并打印。没有NamesAges的全局引用:

def listMembers(Members):               
    for t in zip(*Members):
        print(", ".join(map(str, t)))

Names = ["John","William","Sarah"] 
Ages = [22,33,44]
Members=[Names,Ages]

listMembers(Members)

这是输出:

John, 22
William, 33
Sarah, 44