列表理解附加字符串以列出每个列表项
List Comprehension to append string to list each list item
我目前正在尝试学习 Twitter API,我正在研究一种方法,该方法将为线程 post 准备一个由 |
分隔的字符串,并且将推文的数量附加到列表的每个元素。举个例子:
tweet_thread = "this is going|to be a multipart|tweet thread about python"
tweets = (tweet_thread.split('|'))
tweet_list = []
count = 1
total = len(tweets)
if total > 1:
for item in tweets:
tweet_count = " " + str(count) + "/" + str(total)
tweet_list.append(item + tweet_count)
count +=1
这个returns我想要的:
['this is going 1/3', 'to be a multipart 2/3', 'tweet thread about python 3/3']
但我认为必须有更多的elegant/pythonic方法来做到这一点,也许需要理解?
任何指导将不胜感激!
谢谢
使用枚举:
[elem+' '+str(i+1)+'/3' for i, elem in enumerate(tweet_thread.split('|'))]
使用f-string
和list comprehension with enumerate
:
tweet_thread = tweet_thread.split('|')
result = [f"{i} {index}/{len(tweet_thread)}" for index,i in enumerate(tweet_thread,1)] # not hardcoding length here.
我目前正在尝试学习 Twitter API,我正在研究一种方法,该方法将为线程 post 准备一个由 |
分隔的字符串,并且将推文的数量附加到列表的每个元素。举个例子:
tweet_thread = "this is going|to be a multipart|tweet thread about python"
tweets = (tweet_thread.split('|'))
tweet_list = []
count = 1
total = len(tweets)
if total > 1:
for item in tweets:
tweet_count = " " + str(count) + "/" + str(total)
tweet_list.append(item + tweet_count)
count +=1
这个returns我想要的:
['this is going 1/3', 'to be a multipart 2/3', 'tweet thread about python 3/3']
但我认为必须有更多的elegant/pythonic方法来做到这一点,也许需要理解?
任何指导将不胜感激!
谢谢
使用枚举:
[elem+' '+str(i+1)+'/3' for i, elem in enumerate(tweet_thread.split('|'))]
使用f-string
和list comprehension with enumerate
:
tweet_thread = tweet_thread.split('|')
result = [f"{i} {index}/{len(tweet_thread)}" for index,i in enumerate(tweet_thread,1)] # not hardcoding length here.