如何判断函数输出是否存在于列表中并分至不同列表存储?
Got it, let's tweak your code to fit the new logic you described. First, I renamed the sum variable to sum_val—since sum is a built-in Python function, using it as a variable name can cause unexpected issues later on. I also added a second empty list (I called it myOtherList, feel free to rename it to something more descriptive for your use case) and wrapped the check-and-add logic into a helper function to keep things clean.
Here's the updated code:
myUniqueList = [] myOtherList = [] # New empty list for values not present in myUniqueList def add_Item_To_List(item): sum_val = item + 36 return sum_val def add_to_correct_list(value): # Check if the value exists in myUniqueList if value in myUniqueList: myUniqueList.append(value) else: myOtherList.append(value) # Test the functions with your original variables var = 37 var2 = add_Item_To_List(var) add_to_correct_list(var2) var3 = add_Item_To_List(var2) add_to_correct_list(var3) var4 = add_Item_To_List(var3) add_to_correct_list(var4) # Print both lists to verify the result print("myUniqueList:", myUniqueList) print("myOtherList:", myOtherList)
How It Works:
- We start with two empty lists:
myUniqueList(your original list) andmyOtherListfor values that aren't inmyUniqueList. - The
add_Item_To_Listfunction stays mostly the same, just with the safer variable name. - The new
add_to_correct_listfunction handles the core logic: it checks if the calculated value is already inmyUniqueList. If it is, we add it tomyUniqueList; if not, we send it tomyOtherList. - We use this helper function each time we get a value from
add_Item_To_Listto avoid repeating the check logic over and over.
Example Output:
When you run this code, since none of the calculated values (73, 109, 145) are in the initially empty myUniqueList, all of them will end up in myOtherList:
myUniqueList: [] myOtherList: [73, 109, 145]
If you want to test the "exists" case, you could add something like this before calculating var2:
myUniqueList.append(73)
Then var2 (which is 73) will be added to myUniqueList instead of myOtherList.
内容的提问来源于stack exchange,提问作者cams

