s = "David Joyner, Ashok Goel, Nic Papin"
s_list = s.split()
s_result = ""
for i,name in enumerate(s_list):
# Even number elements are first names and should be turned into single letters.
if i % 2 == 0:
inital = name[0]
else:
# Since we only split on spaces, in the odd case, name has a comma already appended.
s_result += name + " " + inital + "., "
# [:-2] removes both the trailing space and the comma.
print(s_result[:-2])
# Joyner, D., Goel, A., Papin N.
稍微简单一点的版本是:
s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for name in names:
first, last = name.split()
result += last + ', ' + first[0] + '., '
print(result[:-2])
s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for index, name in enumerate(names):
first, last = name.split()
# Checks if index is lower than last.
if index < (len(names) - 1):
result += last + ', ' + first[0] + '., '
else:
result += '& ' + last + ", " + first[0] + '.'
print(result)
s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for name in names[:-1]:
first, last = name.split()
result += last + ', ' + first[0] + '., '
# Final element operation.
first, last = names[-1].split()
result += '& ' + last + ", " + first[0] + '.'
print(result)
s = "David Joyner, Ashok Goel, Nic Papin"
fl_names = [name.split() for name in s.split(",")]
formatted_names = ["{0}, {1}.".format(last, first[0]) for first, last in fl_names]
result = ", ".join(formatted_names)
你也可以用嵌套的列表理解把所有的东西塞进一起,但是你可以看到这会变得很难快速阅读。你知道吗
", ".join(["{0}, {1}.".format(last, first[0])
for first, last in [name.split() for name in s.split(",")]])
这应该管用。你知道吗
稍微简单一点的版本是:
但是涉及到一个额外的
split
操作,如果您有大量的名称(否则这将是一个可以忽略不计的更改),那么它将变得更慢。你知道吗使用姓氏做一些特定的事情:
因此,如果要对列表的最后一个元素执行特定操作,可以通过两种方式执行:
最具python风格的是像第一个示例中那样使用
enumerate
,并捕获index == len(list) - 1
(最后一个元素)的情况:但是,如果您坚决反对使用
enumerate
,那么您可以通过只遍历列表中倒数第二个元素并在循环外执行最后一个操作来获得相同的行为:实际上,您应该只使用
enumerate
,这是它的预期用例。不管您选择哪种算法,您都会注意到我们打印的是result
,而不是result[:-2]
。这是因为我们不再像以前那样在姓氏中添加不必要的字符。你知道吗as far as i've gotten on the updated question with "and" and "&"
查看list comprehensions、str.join和str.format。如果您经常使用python,您会发现它们都非常有用。你知道吗
你也可以用嵌套的列表理解把所有的东西塞进一起,但是你可以看到这会变得很难快速阅读。你知道吗
相关问题 更多 >
编程相关推荐