Python:将一堆列表绑在一起(如Excel列)

时间:2017-04-04 22:48:23

标签: python

我已经习惯了Excel,所以我很难想到如何在Python中做这样的事情(这对我编码新手没有帮助)。在Excel中,我有一列数字,一个字母,一个类别,并且很容易得到我正在寻找的东西。我试图在Excel中链接列的方式中搜索“绑定”列表,但我认为我的术语/思维方式已关闭。

我有两个列表,每个元素与另一个元素“链接”,例如a = 2:

[a, b, c, d]
[2, 7, 5, 6]

我在另一个文件categories.txt中有另一组列表:

[‘a’, ‘color’, ‘blue’]
[‘b’, ‘color’, ‘green’]
[‘c’, ‘fruit’, ‘apple’]
[‘d’, ‘color’, ‘blue’]

我想以某种方式将所有这些信息组合成一种格式,我可以要求颜色或蓝色并获取数字,也许是另一组列表,如:

输出(?):

[color, blue, 8]   #‘a’ and ‘d’ are added to get 8, since they’re both blue
[color, green, 7]
[fruit, apple, 5]

如果对输出格式很重要,最终会将其发送到R,这样我就可以看到我在颜色类别中有多少蓝色(8),有多少绿色(7)等等。字典工作可能吗?我已经阅读了文档和O'Reilly的词典部分,但它们似乎并不合适。

2 个答案:

答案 0 :(得分:0)

这可能是您的一个选择。您可以创建一个包含所有信息的对象。您可以像我一样使用列表,甚至可以标记您传入的每个属性,只检查其中一个属性。

class ColourGroup:
    def __init__(self, data):
        self.data = data

    def has_item(self, item):
        if item in self.data:
            return True
        else:
            return False

colour_groups = [        
    ColourGroup([2, 'a', 'color', 'blue']),
    ColourGroup([7, 'b', 'color', 'green']),
    ColourGroup([5, 'c', 'fruit', 'apple']),
    ColourGroup([6, 'd', 'color', 'blue']),
]

def get_colour_group(colour_groups, option):
    return_groups = []
    for colour_group in colour_groups:
        if colour_group.has_item(option):
            return_groups.append(colour_group.data)
    return return_groups

print(get_colour_group(colour_groups, 'blue'))

答案 1 :(得分:0)

首先,获取一个关联列表[a, b, c, d]的字典 [2, 7, 5, 6]一起使用zip()

alpha_list = [a, b, c, d]
num_list = [2, 7, 5, 6]

lookup_dict = dict(zip(alpha_list, num_list))

现在,假设您的列表列表存储如下(假设您有一段代码将您的文件解析为列表列表):

from collections import defaultdict

category_lists = [[‘a’, ‘color’, ‘blue’], [‘b’, ‘color’, ‘green’], [‘c’, ‘fruit’, ‘apple’], [‘d’, ‘color’, ‘blue’]]

# Lookup the relevant number (from the above dict) for each category list 
# Sum up according to category + color (eg. 'color blue')
# The below builds up a dictionary like this (for the sample data):
# { 'color blue': 8,
#   'color green': 7,
#   'fruit apple': 5
# }
# where from the code, the key into our dict is category_list[1]+' '+category_list[2] 
# eg. 'color blue'
# and the alphabet code at category_list[0] is looked up using the dict above 
# and added to the running total for 'color blue'

my_groups = defaultdict(int)
for category_list in category_lists:
    my_groups[category_list[1]+' '+category_list[2]] += lookup_dict[category_list[0]]

# To view your output:
for key in my_groups:
    out_list = key.split(' ')
    out_list.append(my_groups[key])
    print out_list