如何在传入为非时避免“1”

2022-09-28 19:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

当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

Tags: orselfnonestringreturnifconcol2col3col1expectedcombinedincomingcol4incoming2
1条回答
网友
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

热门问题