如何在Python中创建二维数组?

如何在Python中创建二维数组?,python,Python,我想用python创建二维数组,如下所示: n1 n2 n3 n4 n5 w1 1 4 0 1 10 w2 3 0 7 0 3 w3 0 12 9 5 4 w4 9 0 0 9 7 a = [ [1, 4, 0, 1, 10], [3, 0, 7, 0, 3], [0, 12, 9, 5, 4], [9, 0, 0, 9, 7] ] 其中w1 w2。。。是不同的词,n1 n2 n3是不同的博客。 如

我想用python创建二维数组,如下所示:

     n1 n2 n3 n4 n5

w1   1  4  0  1 10

w2   3  0  7  0  3

w3   0  12 9  5  4

w4   9  0  0  9  7
a = [
    [1, 4, 0, 1, 10],
    [3, 0, 7, 0, 3],
    [0, 12, 9, 5, 4],
    [9, 0, 0, 9, 7]
]
其中w1 w2。。。是不同的词,n1 n2 n3是不同的博客。

如何实现这一点?

如果列表中的元组或DICT不能使用,请考虑使用:


我根本不会创建任何列表,也不会创建二维数组,而是创建一个由x和y头键控的字典,作为元组。例如:

data["w1", "n1"] = 1
这可以看作是一种“稀疏矩阵”表示。根据您想要对数据执行的操作,您也可能需要一个dict of dict,其中外部dict的键是xheader或yheader,而内部dict的键是相反的

假设元组作为键表示,将数据表作为输入:

text = """\
     n1 n2 n3 n4 n5

w1   1  4  0  1 10

w2   3  0  7  0  3

w3   0  12 9  5  4

w4   9  0  0  9  7
"""

data = {}
lines = text.splitlines()
xheaders = lines.pop(0).split()
for line in lines:
    if not line.strip():
        continue
    elems = line.split()
    yheader = elems[0]
    for (xheader, datum) in zip(xheaders, elems[1:]):
        data[xheader, yheader] = int(datum)
print data
print sorted(data.items())
印刷品生产:

{('n3', 'w4'): 0, ('n4', 'w2'): 0, ('n2', 'w2'): 0, ('n1', 'w4'): 9, ('n3', 'w3'): 9, ('n2', 'w3'): 12, ('n3', 'w2'): 7, ('n2', 'w4'): 0, ('n5', 'w3'): 4, ('n2', 'w1'): 4, ('n4', 'w1'): 1, ('n5', 'w2'): 3, ('n5', 'w1'): 10, ('n4', 'w3'): 5, ('n4', 'w4'): 9, ('n1', 'w3'): 0, ('n1', 'w2'): 3, ('n5', 'w4'): 7, ('n1', 'w1'): 1, ('n3', 'w1'): 0}
[(('n1', 'w1'), 1), (('n1', 'w2'), 3), (('n1', 'w3'), 0), (('n1', 'w4'), 9), (('n2', 'w1'), 4), (('n2', 'w2'), 0), (('n2', 'w3'), 12), (('n2', 'w4'), 0), (('n3', 'w1'), 0), (('n3', 'w2'), 7), (('n3', 'w3'), 9), (('n3', 'w4'), 0), (('n4', 'w1'), 1), (('n4', 'w2'), 0), (('n4', 'w3'), 5), (('n4', 'w4'), 9), (('n5', 'w1'), 10), (('n5', 'w2'), 3), (('n5', 'w3'), 4), (('n5', 'w4'), 7)]

假设每个blog中的文本都可以作为字符串使用,并且您在
blogs
中有此类字符串的列表,这就是创建矩阵的方式

import re
# Sample input for the following code.
blogs = ["This is a blog.","This is another blog.","Cats? Cats are awesome."]
# This is a list that will contain dictionaries counting the wordcounts for each blog
wordcount = []
# This is a list of all unique words in all blogs.
wordlist = []
# Consider each blog sequentially
for blog in blogs:
    # Remove all the non-alphanumeric, non-whitespace characters,
    # and then split the string at all whitespace after converting to lowercase.
    # eg: "That's not mine." -> "Thats not mine" -> ["thats","not","mine"]
    words = re.sub("\s+"," ",re.sub("[^\w\s]","",blog)).lower().split(" ")
    # Add a new dictionary to the list. As it is at the end,
    # it can be referred to by wordcount[-1]
    wordcount.append({})
    # Consider each word in the list generated above.
    for word in words:
        # If that word has been encountered before, increment the count
        if word in wordcount[-1]: wordcount[-1][word]+=1
        # Else, create a new entry in the dictionary
        else: wordcount[-1][word]=1
        # If it is not already in the list of unique words, add it.
        if word not in wordlist: wordlist.append(word)

# We now have wordlist, which has a unique list of all words in all blogs.
# and wordcount, which contains len(blogs) dictionaries, containing word counts.
# Matrix is the table that you need of wordcounts. The number of rows will be
# equal to the number of unique words, and the number of columns = no. of blogs.
matrix = []
# Consider each word in the unique list of words (corresponding to each row)
for word in wordlist:
    # Add as many columns as there are blogs, all initialized to zero.
    matrix.append([0]*len(wordcount))
    # Consider each blog one by one
    for i in range(len(wordcount)):
        # Check if the currently selected word appears in that blog
        if word in wordcount[i]:
            # If yes, increment the counter for that blog/column
            matrix[-1][i]+=wordcount[i][word]

# For printing matrix, first generate the column headings
temp = "\t"
for i in range(len(blogs)):
    temp+="Blog "+str(i+1)+"\t"

print temp
# Then generate each row, with the word at the starting, and tabs between numbers.

for i in range(len(matrix)):
    temp = wordlist[i]+"\t"
    for j in matrix[i]: temp += str(j)+"\t"
    print temp
现在,
matrix[i][j]
将包含单词
wordlist[i]
在blog
blogs[j]
中出现的次数,一种方法是使用:


如果您只是想要2D数组而不进行任何解析,可以这样编写:

     n1 n2 n3 n4 n5

w1   1  4  0  1 10

w2   3  0  7  0  3

w3   0  12 9  5  4

w4   9  0  0  9  7
a = [
    [1, 4, 0, 1, 10],
    [3, 0, 7, 0, 3],
    [0, 12, 9, 5, 4],
    [9, 0, 0, 9, 7]
]

用例是什么看起来你们更想要一个2元组(单词,博客):freq dict…我正在做一个数据挖掘项目,在那个里我想收集这样的数据。我知道每个博客的单词数[n1 n1..。我只是创建了一个spradesheet,我已经有了这个值。让我知道用python创建这个值的方法。如果不使用这个值,请看@Jon Clement的评论。但答案取决于你想用这些数据做什么。但是请注意,虽然有各种方法来保存数据,但它们可能与您的示例不一样。您好Kaustubh,请您添加逗号行以便更好地理解我。我正在寻找相同的ans。请对代码进行注释。还有一件事,如果我想打印它,那么如何打印它?我做得太多了,我知道:P无论如何。。。在交互式控制台中复制粘贴整个内容,以查看它的运行情况。