随着 python3 的增加或减少从动态列表中提取元素
Extract elements from dynamic list as increases or decreases in python3
你好,我有一个动态列表,它根据从具有 BeautifulSoup
的站点提取的数据相应地增加或减少
mylist = [a,b,c,d,.......]
如何使以下 fstring 随着列表的增加或减少而动态变化?
fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")
如您所见,我希望 mylist 的元素在 fstring 中由 \nl(新行)分隔,而不是将其连接到字符串。这可能吗?
输出是
the forecast for the week is (choose number):
1. Tuesday 08 2022
2. Wednesday 09 2022
3. Thursday 10 2022
4. Friday 11 2022
您可以为您的列表编写一个循环并将打印语句放入其中。类似于:
my_list = ["a","b","c"]
print(f"the forecast for the week is (choose number):")
for idx, word in enumerate(my_list):
print(f"{str(idx)}. {word}")
print(f"{str(len(my_list))}. Show all week")
这对于您的列表来说应该是动态的
您可以使用 list comprehension
和 enumerate()
创建动态列表和 join()
换行符的元素:
mylist = ['Tuesday 08 2022','Wednesday 09 2022','Thursday 10 2022','Friday 11 2022']
data = '\n'.join([f"{i}. {e}" for i,e in enumerate(mylist,start=1)])
print(f"the forecast for the week is (choose number):\n{data}")
输出
the forecast for the week is (choose number):
1. Tuesday 08 2022
2. Wednesday 09 2022
3. Thursday 10 2022
4. Friday 11 2022
你好,我有一个动态列表,它根据从具有 BeautifulSoup
的站点提取的数据相应地增加或减少mylist = [a,b,c,d,.......]
如何使以下 fstring 随着列表的增加或减少而动态变化?
fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")
如您所见,我希望 mylist 的元素在 fstring 中由 \nl(新行)分隔,而不是将其连接到字符串。这可能吗?
输出是
the forecast for the week is (choose number):
1. Tuesday 08 2022
2. Wednesday 09 2022
3. Thursday 10 2022
4. Friday 11 2022
您可以为您的列表编写一个循环并将打印语句放入其中。类似于:
my_list = ["a","b","c"]
print(f"the forecast for the week is (choose number):")
for idx, word in enumerate(my_list):
print(f"{str(idx)}. {word}")
print(f"{str(len(my_list))}. Show all week")
这对于您的列表来说应该是动态的
您可以使用 list comprehension
和 enumerate()
创建动态列表和 join()
换行符的元素:
mylist = ['Tuesday 08 2022','Wednesday 09 2022','Thursday 10 2022','Friday 11 2022']
data = '\n'.join([f"{i}. {e}" for i,e in enumerate(mylist,start=1)])
print(f"the forecast for the week is (choose number):\n{data}")
输出
the forecast for the week is (choose number):
1. Tuesday 08 2022
2. Wednesday 09 2022
3. Thursday 10 2022
4. Friday 11 2022