我想在Python列表或字典显示表达式中使用本地绑定,以便我可以在多个位置使用复杂表达式的结果(例如,if子句和结果成员表达式)。像这样:
traders = {a:b
for g in groups
for a in account.group_accounts(g)
for b in [account.accounts[a].balance().get_amount()]
if my_condition(b)}
但要实现它,我必须制作一个单身人士名单,这是丑陋和不清楚的。我真的想说
where b = account.accounts[a].balance().get_amount()
但Python显示语法不允许这样的内容。为此目的最好的语法是什么?
答案 0 :(得分:0)
据我所知,原始帖子中的单例列表是将代码保存在单个表达式中的最佳方式。
在python-ideas邮件列表中不时出现为理解中添加一些绑定变量语法的建议。 Here's one from Lie Ryan在2009年,here's one from Mathias Panzenböck在2011年。通常的反对意见是不必要的复杂性:
缺乏本地任务是一项功能。它让人们无法尝试 写过于复杂的单行。 (Carl M. Johnson)
且可读性丧失:
[y for x in xs given f(x) if p(x) else g(x) as y]
- 这只是我,还是其他人发现这个"一串子句" (不管实际的关键词是什么)不是很可读? (Georg Brandl)
答案 1 :(得分:-1)
实施
accounts[a].balance().get_amount()
你可以做这样的事情
class Balance(object):
def __init__(self, money):
self.money = money
def get_amount(self):
return self.money
class Accounts(object):
def __init__(self):
self.accounts = list()
def add(self, *args, **kwargs):
new_account = Account(*args, **kwargs)
self.accounts.append(new_account)
return new_account
def __getitem__(self, item):
return self.accounts[item]
class Account(object):
accounts = []
def __init__(self, name, money):
self.name = name
self.balance = Balance(money)
accounts = Accounts()
accounts.add(name="1", money=42)
accounts.add(name="2", money=24)
accounts.add(name="3", money=33)
print accounts[0].balance.get_amount()
将打印
42
Python实现了许多编程范式,不仅仅是命令式的,所以你应该用pandas和sqlalchemy这样的库来观察相同的语法。