如何在列表中连接日期和时间?

2024-09-29 05:21:35 发布

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

我有一个列表,如下所示:

my_list = 
[['BCN', '01-01-2021', '08:30:30'],
 ['MCR', '01-01-2021', '12:48:12'],
 ['TNG', '01-01-2021', '10:01:02']]

对于my_list中的每个列表,我试图加入index[1]+index[2]并将其写回新列表

这是我的代码:

new_list = []
for row in my_list:
    ' '.join(row[1] + row[2])
    new_list.append(row)

print(new_list)

这是我的输出:

[['BCN', '01-01-2021', '08:30:30'],
 ['MCR', '01-01-2021', '12:48:12'], 
 ['TNG', '01-01-2021', '10:01:02']]

这是我的预期输出:

[['BCN', '01-01-2021 08:30:30'], 
 ['MCR', '01-01-2021 12:48:12'], 
 ['TNG', '01-01-2021 10:01:02']]

Tags: 代码in列表newforindexmylist
3条回答

这一行中没有赋值,也没有执行预期的操作,因为它首先附加字符串(+),然后在每个字符之间放置空格(联接):

    ' '.join(row[1] + row[2])

这就是你想要做的:

for row in my_list:
    new_list.append(row[0])
    new_list.append(row[1] + ' ' + row[2])

您没有更改行的值

尝试:

for row in my_list:
    row = [row[0], ' '.join([row[1], row[2]])]
    new_list.append(row)

您只是添加每行的最后两个元素,而不是将其分配到任何位置。试试这个:

new_list = []
for row in my_list:
    new_list.append([row[0], ' '.join(row[1:])])

print(new_list)
# Output
# [['BCN', '01-01-2021 08:30:30'], 
#  ['MCR', '01-01-2021 12:48:12'], 
#  ['TNG', '01-01-2021 10:01:02']]

较短的版本为:

>>> [[first, ' '.join(rest)] for first, *rest in my_list]

[['BCN', '01-01-2021 08:30:30'],
 ['MCR', '01-01-2021 12:48:12'],
 ['TNG', '01-01-2021 10:01:02']]

编辑:

>>> my_list

[['BCN', '01-01-2021', '08:30:30', 'other0'],
 ['MCR', '01-01-2021', '12:48:12', 'other1'],
 ['TNG', '01-01-2021', '10:01:02', 'other2']]

>>> new_list = []
>>> for row in my_list:
...     new_list.append([row[0], ' '.join(row[1:3]), row[-1]])

>>> new_list
[['BCN', '01-01-2021 08:30:30', 'other0'],
 ['MCR', '01-01-2021 12:48:12', 'other1'],
 ['TNG', '01-01-2021 10:01:02', 'other2']]

或者

>>> [[first, ' '.join(rest), last] for first, *rest, last in my_list]

[['BCN', '01-01-2021 08:30:30', 'other0'],
 ['MCR', '01-01-2021 12:48:12', 'other1'],
 ['TNG', '01-01-2021 10:01:02', 'other2']]

更多项目:

>>> new_list = []
>>> for row in my_list:
...     new_list.append([row[0], ' '.join(row[1:3]), *row[3:]])

相关问题 更多 >