【问题标题】:How to avoid '1' when incoming is none没有传入时如何避免'1'
【发布时间】:2019-03-21 06:09:36
【问题描述】:

当incoming2 和incoming3 为none 时我想要结果,那么它应该避免在incoming1 和incoming4 之间打印两个'1'。

def string_con(self,combined):
    if combined is none:
       return '1'
    else:
       return str(combined)

if incoming['col1'] or incoming['col1'] or incoming['col3'] or incoming['col4']:    
combined = self.string_con(incoming['col1'])+'1'+self.string_con(incoming['col2'])+'1'+self.string_con(incoming['col3'])+'1'+self.string_con(incoming['col4'])
Input1 : incoming['col1']=a incoming['col4']=d
Output1: a1111d 
Expected output1:a1d 
Input2: incoming['col1']=a incoming['col2']=b 
Output2: a1b11 
Expected output2:a1b

【问题讨论】:

  • 你的代码有错别字 --> if incoming['col1'] or incoming['col1'] ...猜第二个应该是incoming['col2'] ...这是你的错误来源吗?
  • 有人可以清理一下英文吗?我不太确定要问什么。
  • None,而不是 none。大写很重要。

标签: python python-3.x python-2.7


【解决方案1】:

您可以尝试以下方法吗:

req_keys = ['col1', 'col2', 'col3', 'col4']
all_list = [incoming[i] for i in req_keys]
all_list = [i for i in all_list if i]
print('1'.join(all_list))

例子:

incoming = {}
incoming['col1'] = 'a'
incoming['col2'] = None
incoming['col3'] = 'c'
incoming['col4'] = None

输出:

a1c

另一个例子:

incoming = {}
incoming['col1'] = 'a'
incoming['col2'] = None
incoming['col3'] = None
incoming['col4'] = 'd'

输出:

a1d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-11
    • 2018-11-30
    • 1970-01-01
    • 2018-07-27
    • 2023-03-11
    • 1970-01-01
    • 2020-10-28
    • 2021-04-19
    相关资源
    最近更新 更多