列表理解逻辑不起作用,我不确定为什么

时间:2019-07-16 14:30:26

标签: python list-comprehension

我正在做的练习要求我创建并打印出包含以下两个列表中所有常见元素的列表,且不重复:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

我正在尝试在一行代码中创建新列表,我认为我的逻辑是正确的,但显然在某处存在问题。

这是当前不起作用的内容:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

common_list = []

common_list = [nums for nums in a if (nums in b and nums not in common_list)]

print(common_list)

我希望得到[1, 2, 3, 5, 8, 13],但是即使我具有'nums not common_list'条件,仍然会重复1,所以我最终得到 [1, 1, 2, 3, 5, 8, 13]

5 个答案:

答案 0 :(得分:1)

建议不要使用列表,而应使用列表以避免重复的值。

common_set = set()

您可以通过以下方式添加项目:

common_set.add(value)

最后,您可以通过以下方式打印值:

print(common_set)

答案 1 :(得分:0)

您可以使用枚举:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


res = [i for n, i in enumerate(a) if i not in a[:n] and i in b]
print (res)

输出:

[1, 2, 3, 5, 8, 13]

答案 2 :(得分:0)

使用列表执行此操作的一种方法是(假设列表中的一个没有重复项):

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

c = [x for x in a if x in b]

print(c)
# [1, 2, 3, 5, 8, 13]

或者,对于任何列表:


a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

c = []
for x in a + b:
    if x in a and x in b and x not in c:
        c.append(x)

print(c)
# [1, 2, 3, 5, 8, 13]

但是set更适合于此:

a = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}
b = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}

c = a.intersection(b)
print(c)
# {1, 2, 3, 5, 8, 13}

答案 3 :(得分:0)

正如其他答案和评论中已经提到的那样,您的问题是,在列表理解过程中,common_list为空。

现在寻求实际解决方案:如果顺序不重要,sets是您的朋友:

common_list = list(set(a) & set(b))

如果订单很重要,sets仍然是您的朋友:

seen = set()
bset = set(b) # makes `in` test much faster
common_list = []

for item in a:
    if item in seen:
        continue
    if item in bset:
        common_list.append(item)
        seen.add(item)

答案 4 :(得分:0)

单线:

    async function runSample(sender_psid, projectId = process.env.DIALOGFLOW_ID) {
      // A unique identifier for the given session
      const sessionId = uuid.v4();

      // Create a new session
      const sessionClient = new dialogflow.SessionsClient();
      const sessionPath = sessionClient.sessionPath(projectId, sessionId);

      // The text query request.
      const request = {
        session: sessionPath,
        queryInput: {
          text: {
            // The query to send to the dialogflow agent
            text: received_message.text,
            // The language used by the client
            languageCode: 'it-IT',
          },
        },
      };

      // Send request and log result
      const responses = await sessionClient.detectIntent(request);
      console.log('Detected intent');
      console.log("TRUE ALL: ");
      console.log(JSON.stringify(responses));
      const result = responses[0].queryResult;
      //console.log(`ALL:  ${JSON.stringify(result)}`);
      console.log(`  Query: ${result.queryText}`);
      console.log(`  Response: ${result.fulfillmentText}`);
      if (result.intent) {
        console.log(`  Intent: ${result.intent.displayName}`);
      } else {
        console.log(`  No intent matched.`);
      }

      let response;
      response = {
        "text": result.fulfillmentMessages[0].text.text[0],
      }
      callSendAPI(sender_psid, response);
    }
    runSample(sender_psid);