简体   繁体   English

Python 3 | 将字符串附加到列表中的项目?

[英]Python 3 | Appending a string to an item in a list?

After trying many different methods for this problem, such as nested for loops (which iterate over the first list as many times as the length of the second iteration), and I've tried .join which I couldn't get to do what I wanted. 在尝试了许多不同的方法来解决此问题之后,例如嵌套的for循环(迭代第一个列表的次数与第二个迭代的长度一样多),而我尝试了.join ,但我无法做通缉。


Here is the problem... 这是问题所在...

I am using two for loops to append the same list. 我正在使用两个for循环来追加相同的列表。

The first for loop: 第一个for循环:

for friend in individual_friends:
    friends.append(friend.text)

Which gives me: 这给了我:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends',
 ...., 
'Jayde Woods\n56 mutual friends\n4 new posts\nFriends']

the second for loop: 第二个for循环:

for link in individual_friends_links:
    links = link.get_attribute("href")
    friends.append(links)

Which gives me: 这给了我:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends', 
..., '
Jayde Woods\n56 mutual friends\n4 new posts\nFriends', 
'https://m.facebook.com/jodyannelizabeth.lill?ref=bookmarks', 
..., 
'https://m.facebook.com/jayde.woods?ref=bookmarks']

What I actually want is: 我真正想要的是:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends\nhttps://m.facebook.com/jodyannelizabeth.lill?ref=bookmarks', 
..., 
'Jayde Woods\n56 mutual friends\n4 new posts\nFriends\nhttps://m.facebook.com/jayde.woods?ref=bookmarks']

The Error 错误

The mistake you are making is that, by calling append , you are always adding to the end of friends . 您犯的错误是,通过调用append ,您总是会添加到friends末尾

But for your links, you don't want to add to the end of friends , you want to change the value of an element already in friends . 但是对于您的链接,您不想添加到friends的末尾,您想要更改已经在friends中的元素的值。

The Solution 解决方案

You need something more like this: 您需要这样的东西:

# create your list of friends
for friend in individual_friends:
    friends.append(friend.text)

# for every *i*th link, look up the *i*th friend in `friends`,
# and modify that value, instead of adding to the end of `friends`.
for link_index, link in enumerate(individual_friend_links):
    friends[link_index] = friends[link_index] + '\n' + link.get_attribute("href")

The Better Solution 更好的解决方案

But this is verbose. 但这很冗长。 There is no need to do two explicit for -loops. 不需要for -loops做两个显式for You need the power of zip , which will merge your two separate lists into a single list of 2-tuples and do exactly the same as the above. 您需要zip ,它将两个单独的列表合并为一个由2个元组组成的列表,并且与上述功能完全相同。

for friend, link in zip(individual_friends, individual_friends_links):
    friends.append(friend.text + '\n' + link.get_attribute("href")) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM