Python如何在每个其他列出的项目中插入字符

2024-09-29 23:18:11 发布

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

list = ['username1', 'https://link.com/bsd3nj', 'username2', 'https://link.com/a32fs2', 'username3', 'https://link.com/cfzxso']

sort_list = '* {}'.format('- \n'.join(list))

输出:

* username1- 
https://link.com/bsd3nj-
username2- 
https://link.com/a32fs2-
username3- 
https://link.com/cfzxso-
username4- 
https://link.com/a235jsh-
username5- 
https://link.com/123nls2-

这是我所拥有的,但不是我想要的

我希望名单是这样的

* username1 - https://link.com/bsd3nj
* username2 - https://link.com/a32fs2
* username3 - https://link.com/cfzxso
* username4 - https://link.com/a235jsh
* username5 - https://link.com/123nls2

我曾想过做.split(),但实际上没有任何模式。用户名是随机的,因此它会显示链接的结尾


Tags: httpscomformatlinksortlistusername2username1
3条回答

使用迭代器是一种有效的解决方案:

def joined(given_list):
    iterator = iter(given_list)
    return '\n'.join(['* ' + c + ' - ' + next(iterator) for c in iterator])

以下为一行:

l = ['username1', 'https://link.com/bsd3nj', 'username2', 'https://link.com/a32fs2', 'username3', 'https://link.com/cfzxso']

out = '* {}'.format('\n* '.join(list(map(" - ".join, zip(l[::2], l[1::2])))))

您不应该为变量使用内置名称:list,如果您不考虑它,它会让您一天都不会出错


也就是说,要从连续的元素中进行配对,有几个选项(listed here

这里有一个:zip(values[::2], values[1::2])

for name, link in zip(values[::2], values[1::2]):
    print(f"*{name} - {link}")

# or shorter

sort_list = "\n".join([f"*{name} - {link}" for name, link in zip(values[::2], values[1::2])])
print(sort_list, "\n\n")

切片表示法[start:end:increment]在这里

  • [::2]:从开始的所有值,2乘2=>;所有的名字
  • [1::2]:除第一个值外的所有值,2乘2=>;所有链接

{a2}操作生成一个迭代器,该迭代器聚合来自每个iterable的元素

zip([1,2,3], ['a', 'b', 'c']) # => ((1,'a'), (2, 'b'), ('3, 'c'))

因此,您有一个名称列表和一个链接列表,并将它们配对

print(values[::2])  # ['username1', 'username2', 'username3']
print(values[1::2])  # ['https://link.com/bsd3nj', 'https://link.com/a32fs2', 'https://link.com/cfzxso']
print(list(zip(values[::2], values[1::2]))) # [('username1', 'https://link.com/bsd3nj'), ('username2', 'https://link.com/a32fs2'), ('username3', 'https://link.com/cfzxso')]

相关问题 更多 >

    热门问题