python替换列表的数据_使用惟一ID Python将2D列表中的所有元素替换为其他列表中的数据...

本文通过创建Person类和PersonList类,演示如何根据ID替换2D列表中的元素。Person类用于存储个人数据,PersonList类提供了根据ID获取Person对象的方法。通过示例代码展示了如何使用这些类处理数据,强调了使用对象而非字符串列表的好处。
摘要由CSDN通过智能技术生成

要获得更干净的代码,应该考虑使用类来封装数据。你知道吗

让我们看看:class Person(object):

def __init__(self, identifier, firstname, name, state):

self.id = identifier

self.firstname = firstname

self.name = name

self.state = state

def __repr__(self):

return "".format(self.firstname, self.name, self.id, self.state)

def as_list(self):

return [self.firstname, self.name, self.state]

class PersonList(list):

def __init__(self, *args, **kwargs):

list.__init__(self, *args, **kwargs)

def getById(self, identifier):

""" return the person of this list whose the id is equals to the requested identifier. """

# filter(boolean function, iterable collection) -> return a collection hat contain only element that are true according to the function.

# here it is used a lambda function, a inline function declaration that say for any given object x, it return x.id == identifier.

# the list is filtered to only get element with attribut id equals to identifier. See https://docs.python.org/3.4/library/functions.html#filter

tmp = list(filter(lambda x: x.id == identifier, self))

if len(tmp)==0:

raise Exception('Searched for a Person whose id is {0}, but no one have this id.'.format(identifier))

elif len(tmp) > 1:

raise Exception('Searched for a Person whose id is {0}, and many people seem to share this id. id are supposed to be unique.'.format(identifier))

return tmp[0]

##CONSTANTS##

#id list - modified to not instanciate 9 Person

ids = [[1412,2521,3411],#bob, jane, jim

[3411,1412,1412],#jim, bob, bob

[3411,2521,2521]]#jim, jane, jane

#person list

index=PersonList([Person(1412, 'Bob', 'Smith', 'Ohio'),

Person(2521, 'Jane', 'Doe', 'Texas'),

Person(3411, 'Jim', 'Black', 'New York')])

def computeResult(id_list, personList):

personList = [ [personList.getById(identifier) for identifier in subList] for subList in id_list]

resultList= []

for sublist in personList:

tmp = []

for person in sublist:

tmp += person.as_list()

resultList.append(tmp)

return resultList

if __name__ == "__main__":

print(computeResult(ids, index))

因为我的观点是,你用一只手上的数据结构是错误的。应用程序应该处理Person对象之类的事情,而不是字符串列表。反正是你的应用程序。我只是建议您考虑使用personList作为处理数据的更好的数据结构,而不是这个丑陋的列表。

另一方面,如果id像我想的那样是唯一的,如果您成功地将数据放入字典中,例如index={1412 : Person(...), 2500 : Person(...), ...}

或者index={1412: ['Bob', 'Doe', ...], 2500 : [...], ...}`

它确实更实用,因为您可以删除PersonList类,然后仅使用index.get(1412)来获取与id对应的数据

编辑:根据请求添加跟踪示例。你知道吗

此脚本保存在名为“”的文件中柔软的““python3

>>> import sof

>>> sof.index

[, , ]

>>> sof.index.getById(666)

Traceback (most recent call last):

File "", line 1, in

File "/home/vaisse/Bureau/sof.py", line 25, in getById

raise Exception('Searched for a Person whose id is {0}, but no one have this id.'.format(identifier))

Exception: Searched for a Person whose id is 666, but no one have this id.

如你所见,一旦出错,一切都会停止。如果这种行为不是您想要的,您还可以返回一个None值,并在某个地方跟踪失败的内容,而不是增加一个Exception,然后继续处理数据。如果你想让你的应用程序在出错的情况下仍然运行,你应该看看https://docs.python.org/3.1/library/warnings.html。否则,提出一个简单的例外就足够了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值