python - 是否可以通过理解为列表做嵌套条件?
问题描述
我正在挑战自己变成这样的东西
if a and b and c:
do_something(x) ## some function
elif a and b and c and d
do_something(x[:-1]) ## the same function but slightly different
像这样
cosa = [do_something(x) for x in X if a and b and c
or
do_something(x[:-1]) for x in X if a and b and c and d]
在 Python 中可能吗?我已经被告知要使用 for 循环,但我很想知道是否有办法处理这个问题,因为 functiondo_something
的行为只有一点点变化。
我想要做的更具体的描述:
history[chat_name] = [chats.message('chat_type',
line.split(',',4)[3],
line.split(',',4)[1],
line.split(',',4)[2],
line.split(',',4)[4][:-1])
for line
in file
if line.split(',',4)[0] == chat_type
and line.split(',',4)[2] == chat_name]
我正在编写一个应该模拟聊天应用程序的代码。该变量chat_type
指示它是群聊 ('grupo') 还是个人聊天 ('regular')。因为,当谈到一个聊天组时,只要他们在组中,谁发送消息并不重要,这个代码就足够了,可以完成工作。
但是,当涉及到个人聊天时,上面的代码使代码包括任何人写给给定收件人的所有消息。我想添加一个条件,即当且仅当 chat_type 设置为“常规”时,代码必须确保发件人是当前用户。
我固定如下:
if chat_type == 'grupo':
history[chat_name] = [chats.message('chat_type',
line.split(',',4)[3],
line.split(',',4)[1],
line.split(',',4)[2],
line.split(',',4)[4][:-1])
for line
in file
if line.split(',',4)[0] == chat_type
and line.split(',',4)[2] == chat_name]
elif chat_type == 'regular':
history[chat_name] = [chats.message('chat_type',
line.split(',',4)[3],
line.split(',',4)[1],
line.split(',',4)[2],
line.split(',',4)[4][:-1])
for line
in file
if line.split(',',4)[0] == chat_type
and line.split(',',4)[2] == chat_name
and line.split(',',4)[1] == self.username] ##this is the extra condition
我希望这有助于回答我的问题。
解决方案
这应该是做你需要的正确方法
cosa = [do_something(x) if a and b and c else do_something(x[:-1]) if a and b and c and d for x in X]
推荐阅读
- c# - 我可以将 Jobject 与 OData 一起使用吗?
- jmeter - 如何在 Jmeter 中随机发送不同的参数和值来请求
- android - 在服务器上进行更改后刷新 FirebaseUser
- django - 无法导入 django_countries 尚未安装
- sql - 如何获取postgres中的字段计数?
- swift - Vision 和 CoreML – CGImagePropertyOrientation 需要错误的类型
- mysql - ECS 上带有 mysql 和 .war 文件的 Docker 映像
- python - 在 Python 中使用 Chudnovsky 算法计算 Pi 时我变得不准确
- mysql - 在 column == 0 的最后一行之后选择 column > 0 的行
- javascript - React.js:使用 material-ui 在表格中添加操作图标(编辑、删除)