Skip to main content
 首页 » 编程设计

python之有没有办法根据条件语句从各种列表中删除项目

2024年11月24日8findumars

我正在编写一个程序,该程序将充当纽约摄影师的摄影创意生成器。它现在的工作方式非常简单,代码利用 random.choice 函数从列表中随机提取项目,然后代码以形成英语句子的方式打印出来作为最终结果。

我的问题是我需要为此添加一些逻辑,因为有些结果对摄影师来说没有意义(至少在我看来)。在这个例子中,我试图从 technique_list 中删除“Bracketed (HDR)”,如果在 python 选择主题项时恰好随机选择了“Portrait”。

我感觉我在条件 if 语句中误用了 .remove 函数。有一个更好的方法吗?我附上了代码的相关部分以供检查。

我已经尝试过 technique_list.remove('Bracketed (HDR)') 以及

del technique_list[0] ,都作为 if 语句的响应部分。

import random  
 
print ("You should try taking a...") 
 
#pool of items that the program will randomly choose.. 
theme_list = ['Cityscape','Peoplescape','Port-Scape', 'Portrait'] 
technique_list  = ['Bracketed (HDR)','Wide Angle', 'Zoom','Long  
Exposure','Fast Shutter','Daytime Long Expo','Timelapse'] 
 
 
#what we need here are conditional IF statements,  that manipulate items  
from various lists 
 
#this bit of code determines the theme of a photo idea 
theme_var = random.choice(theme_list)  
for theme in theme_var: 
if theme == 'Portrait': 
        technique_list.remove('Bracketed (HDR)')  
print("",theme_var) 
 
#this bit of code determines the technique of a photo idea 
technique_var = random.choice(technique_list) 
print("", technique_var) 
 
print("picture, from") 
 
#this line of code determines the location of a photo idea 
location_var = random.choice(location_list) 
print("", location_var)  

这仍然是代码的可能结果之一:

You should try taking a... 
 Portrait 
 Bracketed (HDR) 
picture, from 
 34th Street 
during 
 Sunrise 
and then give it a 
 Black & White 
edit in Lightroom! 
[Finished in 0.2 

正如我之前所说,人像和包围式 (HDR) 永远不应该是同一结果的一部分,这对这种情况没有意义。

请您参考如下方法:

这个问题(我认为)是因为你迭代的是随机选择的结果而不是列表本身,你不需要 for 循环。

theme_var = random.choice(theme_list)  
 
if theme_var == 'Portrait': 
        technique_list.remove('Bracketed (HDR)')  
print("",theme_var) 
 
#this bit of code determines the technique of a photo idea 
technique_var = random.choice(technique_list) 
print("", technique_var) 
 
print("picture, from") 
 
#rest of the code 

应该做