You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断函数输出是否存在于列表中并分至不同列表存储?

Adjusted Code to Meet Your Requirement

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) and myOtherList for values that aren't in myUniqueList.
  • The add_Item_To_List function stays mostly the same, just with the safer variable name.
  • The new add_to_correct_list function handles the core logic: it checks if the calculated value is already in myUniqueList. If it is, we add it to myUniqueList; if not, we send it to myOtherList.
  • We use this helper function each time we get a value from add_Item_To_List to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:38:00