假设我有以下Python列表:
['7831-0', nan, '3165-0', '7831-0', '7831-1']
我想在上面的列表中的每个元素上添加相同的前缀('ADD_'。我也想从列表中删除nan。我想要的输出列表如下:
list = ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']
我尝试了以下代码:
prefix_ADD = 'ADD_'
new_list = [prefix_ADD + x for x in list]
但是出现以下错误:
TypeError: must be str, not float
答案 0 :(得分:0)
[prefix_ADD + x for x in list if not str(x) == "nan"]
是您可以过滤掉Nan的一种方法
答案 1 :(得分:0)
也许不是那么优雅的解决方案,但是如何解决呢?
new_list=[]
old_list = ['7831-0', nan, '3165-0', '7831-0', '7831-1']
prefix_ADD = 'ADD_'
for x in old_list:
if x != nan:
new_list.append(prefix_ADD + x)
print(new_list)
# ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']
答案 2 :(得分:-1)
your_list = ['7831-0', float('nan'), '3165-0', '7831-0', '7831-1']
print(your_list) # ['7831-0', nan, '3165-0', '7831-0', '7831-1']
prefix_ADD = 'ADD_'
new_list = [prefix_ADD + x for x in your_list if isinstance(x, str)]
print(new_list) # ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']