Python:如果元素不在列表中,则添加到新列表

时间:2016-06-14 01:10:03

标签: python

我有一个丑陋的功能,并认为必须有更多的Pythonic方式(大写字母变量是字符串):

def get_missing_header_fields(header):
    missing_fields = []
    if FIRST_NAME not in header:
        missing_fields.append(FIRST_NAME)
    if LAST_NAME not in header:
        missing_fields.append(LAST_NAME)
    if EMAIL not in header:
        missing_fields.append(EMAIL)
    if PHONE not in header:
        missing_fields.append(PHONE)
    if ADDRESS not in header:
        missing_fields.append(ADDRESS)
    if COMPANY not in header:
        missing_fields.append(COMPANY)
    if TITLE not in header:
        missing_fields.append(TITLE)
    return missing_fields

任何记录?

2 个答案:

答案 0 :(得分:4)

你可以使用套装:

FIELDS = set([FIRST_NAME, LAST_NAME, EMAIL, etc...])

def get_missing_header_fields(header):
  return FIELDS.difference(header)

集合为iterables并支持成员资格测试,这通常足以满足大多数用例。如果你真的需要一个列表,只需构建一个:list(FIELDS.difference(header))

答案 1 :(得分:3)

只需使用理解

def get_missing_header_fields(header):
    # Completing the tuple is an exercise for the reader
    fields = (FIRST_NAME, LAST_NAME, ..., TITLE)
    return [field for field in fields if field not in header]

甚至是一套

def get_missing_header_fields(header):
    # Completing the tuple is an exercise for the reader
    fields = set(FIRST_NAME, LAST_NAME, ..., TITLE)
    return list(fields - set(header))