有给定的人员清单。每个人的信息[姓名,生日,技能,薪水]都包含在内部列表中。
people = [['Nigel Toon', '19-12-1985', 'Python, Javascript, Ruby', 5000],
['Maria Raga', '03-08-1992', 'Javascript, C++, C', 7500],
['Risi Kosla', '12-07-1981', 'Julia, Python, R', 4000]]
如何提取生日并将其添加到列表中?
输出应为:
['19-12', '03-08', '12-07']
我尝试使用此代码:
def birthday(people):
birthday_list = []
for person in people:
new_birthday = person[1]
birthday_list.append(new_birthday)
return birthday_list
birthday(people)
我得到此输出:
['19-12-1985', '03-08-1992', '12-07-1981']
谢谢!
一个衬里
['-'.join(p[1].split('-')[:2]) for p in people]
您可以在第一个-
上分割生日,然后将第二个部分追加到列表中。像这样的东西:
new_birthday = person[1].split('-', 1)[1]
birthday_list.append(new_birthday)
通过这种方式,您可以以更少的串联获得所需的内容。
这可以帮助:替换
new_birthday = person[1]
通过:
new_birthday = person[1].split('-')[0]+"-"+person[1].split('-')[1]
您的方法将是:
def birthday(people):
birthday_list = []
for person in people:
new_birthday = person[1].split('-')[0]+"-"+person[1].split('-')[1]
birthday_list.append(new_birthday)
return birthday_list
birthday(people)
your_list = ['19-12-1985', '03-08-1992', '12-07-1981']
birthday = ['-'.join(a.split('-')[:-1]) for a in your_list]
print(birthday)
['19-12', '03-08', '12-07']