繁体   English   中英

列表内的 Python 元组

[英]Python tuple inside list

我有一个如下所示的数据结构,我如何根据名称 append 新值。 就像,如果输入名称是 Sam 并且数量是 200。如果 Sam 已经存在,它应该 append 到 Sam 的列表,否则它应该在列表中创建一个新元素。

data = [('Sam',[100,120,110]),('Andrew',[80,90,100]),('Gram',[400,300,350]),
              ('Jeremy',[125, 100]), ('Mike',[75,30])]

从 python 字典开始将更适合您尝试做的事情。 但我猜你要么有一个你不能使用它的原因,要么你想学习如何遍历一个列表。

这是示例代码:

data = [('Sam',[100,120,110]),('Andrew',[80,90,100]),('Gram',[400,300,350]),
              ('Jeremy',[125, 100]), ('Mike',[75,30])]


## Create a function so you can call this elsewhere
def append_value(name, value):

    ## Itterate through the list
    for each in data:

        ## If the passed name equals a name in your list do something
        if each[0] == name:

            ## Append the value to the list in the tuple
            each[1].append(value)
            
            ## Use return to break the for loop
            ## Return true if a value was added
            return True

    ## If no name in the list equaled the passed name we get here
    ## Return false so we know that something went wrong
    return False

## Print data before addition
## Output: [('Sam', [100, 120, 110]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30])]
print(data)

## Append new number to "sam" and print the return
## Output: True
print(append_value('Sam', 400))

## Print data after addition
## Output: [('Sam', [100, 120, 110, 400]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30])]
print(data)

我评论了每一行,以便您知道它的作用以及将输出提供给打印件。 在不使用 dict 的情况下,您必须手动遍历整个列表。 如果这有帮助或者您有任何问题,请告诉我!

字典更适合您的目的。

data.setdefault(name, []).append(value)

如果您坚持使用现有的元组列表,则迭代所有项目并在元组的零索引处读取名称并相应地继续。 丑陋而低效。

for items in data:
    if item[0] == name:
        name_found = True
        item[1].append(value)
if not name_found:
    data.append((name,[value]))
name_found = False


迭代元组列表并替换/添加元组

作为基本规则,元组是不可变的。 所以你不能改变一个元组。 但是,您可以用列表中的另一个元组替换一个元组。 这就是我们将如何解决您的问题。

这是执行此操作的代码。

data = [('Sam',[100,120,110]),('Andrew',[80,90,100]),('Gram',[400,300,350]),
              ('Jeremy',[125, 100]), ('Mike',[75,30])]

name = input ('Enter name to add to list : ')
while True:
    try:
        value = int (input ('Enter value to add to list : '))
        break
    except:
        print ('not a number')

for i,(nm,vals) in enumerate(data):
    if nm == name:
        vals +=[value]
        data[i] = (nm,vals)
        break
else:
    data.append ((name,[value]))

print (data)

output 如下: 列表中存在名称的示例:

Enter name to add to list : Sam
Enter value to add to list : 250
[('Sam', [100, 120, 110, 250]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30])]

另一个名称在列表中不存在的示例:

Enter name to add to list : Joe
Enter value to add to list : 250
[('Sam', [100, 120, 110]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30]), ('Joe', [250])]

使用字典而不是元组

如果您对替代方法感兴趣,可以将元组列表转换为字典。 然后将数据插入字典,并将其转换回元组列表。

#convert the list of tuples to a dict of lists 
data_dict = {nm:vals for nm,vals in data}

#use setdefault to add the value. append() allows you to append if key exists
data_dict.setdefault(name,[]).append(value)

#convert it back to a list of tuples
data_list = [(nm,vals) for nm,vals in data_dict.items()]

print (data_list)

结果与上述相同。

而简单的迭代可以解决问题。 但是如果你很好奇并且速度是至关重要的,而且不能使用dict那么你可以查看dicthash map是如何工作的。 你可以实现相同的。

这里我举一个例子,但它本身并不平衡,也就是说如果数据结构是满的,你需要扩展列表index假设2次。 但它代表了强调的想法。

class CC:
    index = [None for i in range(100)]
    
    def add_element(self, key, val):
        hash_ = abs(hash(key))
        i_ = hash_ %100
       # it does not check if the index is full, in that case it will
       # be an infinite loop
        while(self.index[i_] !=None):
            if(self.index[i_][0] == key):
                self.index[i_][1].append(val)
                return
            i_ += 1
            
        self.index[i_] = [key, [val]]
        
    def get_cc(self):
        return [i for i in self.index if i is not None]
c = CC()

print(c.get_cc())

>>> []

c.add_element('Sam', 100)
c.add_element('Sam', 120)
c.add_element('Sam', 110)

c.add_element('Andrew', 80)

print(c.get_cc())

>>> [['Andrew', [80]], ['Sam', [100, 120, 110]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM