Python 如何从列表中逐项提取并对其执行新功能
如何在posts\u list=[]中的每个项目上执行新功能 假设我有这个函数Python 如何从列表中逐项提取并对其执行新功能,python,python-3.x,Python,Python 3.x,如何在posts\u list=[]中的每个项目上执行新功能 假设我有这个函数 def hello(): print('Hello post from posts_list') 我想给posts\u list=[] titles = driver.find_elements_by_xpath("//*[@class='item__ad--title']") posts_list = [] def xxx(): for title in titles: x = t
def hello():
print('Hello post from posts_list')
我想给posts\u list=[]
titles = driver.find_elements_by_xpath("//*[@class='item__ad--title']")
posts_list = []
def xxx():
for title in titles:
x = title.get_attribute('href')
posts_list.append(x)
for p in posts_list:
print(f"this is {p}")
print(len(posts_list))
xxx()
这就是你要找的吗
def xxx():
for title in titles:
x = title.get_attribute('href')
posts_list.append(x)
# this should come out of the titles loop,
# since you were currently adding data,
# and then you can traverse through it
for p in posts_list:
# Calling your help(), assuming it does accepts p from your list
help(p)
print(len(posts_list))
# Indentation matters, please look into the Python Indentation,
# this is where you will be calling your method outside your def xxx()
xxx()
您的帮助功能
# def help should accept an argument p, which you will use to print the data
def help(p):
print(f"this is {p}")
我希望这就是你要找的。请仔细阅读本教程,以复习Python的基础知识,因为在编写代码时这确实很重要
感谢并愉快地学习:)原始帖子中的缩进严重扭曲 您试图解决的问题最好通过列表理解来解决:
posts_list = [title.get_attribute('href') for title in titles]
[help(p) for p in posts_list]
如果您对帖子本身不感兴趣,而只对应用help
的结果感兴趣,则可以将这两个循环组合起来:
[help(title.get_attribute('href')) for title in titles]
你想在
posts\u list
的循环中调用hello()
,你想把p
传递给hello()
对吗?是的,这就是我想要的答案@Ihab Hamed,让我知道你的情况