首页 > 解决方案 > 是否可以通过理解为列表做嵌套条件?

问题描述

我正在挑战自己变成这样的东西

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

我希望这有助于回答我的问题。

标签: pythonfor-looplist-comprehension

解决方案


这应该是做你需要的正确方法

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]

推荐阅读