为了账号安全,请及时绑定邮箱和手机立即绑定

将 none 值替换为同一列表中的值

将 none 值替换为同一列表中的值

ibeautiful 2022-09-20 16:01:39
我是python的新手,我正在为这个例子而苦苦挣扎。我想用列表中的日期替换空元素。例如,每个空元素都被星期一替换到星期二...我使用的是蟒蛇2.7。这是我得到的列表:[u'Monday 30 March', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'Tuesday 31 March', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'Wednesday  1 April', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']这就是我尝试过的:for tim in time_d:    if tim =='':        print time_d[0]
查看完整描述

2 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

你在寻找吗?如下所示:


for i, val in enumerate(time_d):

    if not val:

        time_d[i] = time_d[i-1]


time_d

# ['Monday 30 March', 'Monday 30 March', ... ,'Monday 30 March', 

#  'Tuesday 31 March', 'Tuesday 31 March', ... , 'Tuesday 31 March', 

#  'Wednesday  1 April', 'Wednesday  1 April', ..., 'Wednesday  1 April']


查看完整回答
反对 回复 2022-09-20
?
缥缈止盈

TA贡献2041条经验 获得超4个赞

这是一个简单的解决方案(在Python 3中):


dates = ['Monday 30 March', '', '', '', '', '', '', '', '', '', 'Tuesday 31 March', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Wednesday  1 April', '', '', '', '', '', '', '', '', '', '', '', '', '', '']     

newdates = []

current = ''

for item in dates:

    if not item:

        newdates.append(current)

    else:

        current = item

        newdates.append(current)

print(dates)

print(newdates)

带输出:


['Monday 30 March', '', '', '', '', '', '', '', '', '', 'Tuesday 31 March', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Wednesday  1 April', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

['Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Monday 30 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Tuesday 31 March', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April', 'Wednesday  1 April']



查看完整回答
反对 回复 2022-09-20
  • 2 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信