动态布尔列表

2024-04-26 13:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个非常基本的例子。我想保留一个变量/标志列表,但我知道列表是不可变的。在下面的示例中,我可以简单地将一个新元组附加到hasmootstache(以日志类型的方式),但是列表hasmootstache将继续扩展。你知道吗

我有三个问题: 如何替换列表中一个元组中的元素(参见下面示例中的注释),比如在包含sam和sarah的元组中更改bole an? 知道列表是不变的是一种好的做法吗? 有没有其他/更干净的方法来保存一个有限的标志列表?你知道吗

hasmoustache=[('jon',False,'Male'),('sam',False,'Male'),('sarah',False,'Female')]
# hasmoustache is list of tuples describing (name,has a moustache?,gender)

name = 'Joe'
gender = 'Male'
if name not in hasmoustache:
    append hasmoustache.((name,False,gender))

for y in hasmoustache:
    print y

barber=[('jon',1),('sam',8),('sarah',10)]
# barber is a list of tuples describing (name,number of weeks since last visit to the barber)
for m in barber:
    if m[1]>4
        # Do something to change tuple with name=m[0] in hasmoustache to True
        # List in python are immutable so how to do it?

callthem = [x[0] for x in hasmoustache if x[1]]

for y in callthem:
    print y

for y in hasmoustache:
    print y

输出应显示: ('jon',假,'Male') ('sam',假,'Male') ('sarah',假,'Female') ('Joe',假,'Male') 山姆 莎拉 ('jon',假,'Male') ('sam',真的,'Male') (‘莎拉’,真的,‘女性’) ('Joe',假,'Male')


Tags: oftonameinfalse列表forsam
1条回答
网友
1楼 · 发布于 2024-04-26 13:49:42

你倒过来了一点。Lists是可变的,这意味着您可以在创建它们之后修改它们的值,Tuples是不可变的序列类型:这样的对象一旦创建就不能修改。如果你想有一个结构来实现你想要的,你可以使用一个列表列表。你知道吗

barber=[['jon',1],['sam',8],['sarah',10]]

mutable sequence types

所以问题1的答案是。你知道吗

您无法更改元组的元素,因此如果不创建一个全新的元组并用该元组替换列表中的当前元组,您将无法完成预期的操作。你知道吗

问题2。你知道吗

列表不是不变的,所以它不是事件。你知道吗

问题3。你知道吗

您可以使用dict,使用名称作为键,如果它们都是唯一的,并保留一个信息列表作为值。你知道吗

这是一个使用dict的示例:

barber={'jon': 1,'sam':8,'sarah': 10 }

if barber.get("sam")  > 4: # get value of sam
   print barber.get("sam")     
8

把hasmustace也变成一句话:

hasmoustache={'jon':[False,'Male'],'sam':[False,'Male'],'sarah':[False,'Female']}
barber={'jon':1,'sam':8,'sarah':10}

if barber.get("sam")  > 4:
   hasmoustache.get("sam")[0]=  True
print hasmoustache
{'sarah': [False, 'Female'], 'sam': [True, 'Male'], 'jon': [False, 'Male']}

相关问题 更多 >