如何检查Python中的列表中是否存在字符串?

时间:2018-04-13 13:59:11

标签: python json string list

我从API调用中收到以下JSON数据:

<video width="400" controls autoplay>
  <source src="/uploads/2018/04/ML_video-converted-with-Clipchamp.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

使用以下代码将“mediaStream”值作为字符串获取,将此值与字符串列表进行比较,并打印出未出现在列表中的任何值:

[     
       {
        "mediaAlgorithm": "G.722",
        "mediaDirection": "TX",
        "mediaFormat": "---",
        "mediaState": "OPENED",
        "mediaStream": "audioTx",
        "mediaType": "AUDIO",
      },
      {
        "mediaAlgorithm": "G.722",
        "mediaDirection": "RX",
        "mediaFormat": "---",
        "mediaState": "OPENED",
        "mediaStream": "audioRx",
        "mediaType": "AUDIO",
      }
]

由于JSON数据中没有“videoRx”和“videoTx”值,我希望打印语句可以达到两次并将这两个值打印给用户 - 但是从不执行print语句。

最初,我认为语法“如果字符串不在列表”中存在问题 - 但是,以下编译没有错误:

def parse_json_data(json_data):

    my_list = ["audioRx", "audioTx", "videoRx", "videoTx"]

    for media_channel in json_data:
        channel_type = str(media_channel['mediaStream'])

        if channel_type not in my_list:
            print("{0} is not in the list".format(channel_type))

有人能够解释这里发生的事情吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果你想检查json中没有提到哪些通道你应该遍历my_list而不是json_data,即

def parse_json_data(json_data):

    my_list = ["audioRx", "audioTx", "videoRx", "videoTx"]
    channel_types = [media_channel['mediaStream'] for media_channel in json_data]

    for media_channel in my_list:
        if media_channel not in channel_types:
            print("{0} is not in the list".format(media_channel))

答案 1 :(得分:0)

首先,您可能想要检查生成json字符串的方式,因为在mediaType之后需要删除的额外逗号才能成为有效的json字符串。

然后您可以使用any()检查列表中是否存在该值:

import json

json_str = """
    [
           {
            "mediaAlgorithm": "G.722",
            "mediaDirection": "TX",
            "mediaFormat": "---",
            "mediaState": "OPENED",
            "mediaStream": "audioTx",
            "mediaType": "AUDIO"
          },
          {
            "mediaAlgorithm": "G.722",
            "mediaDirection": "RX",
            "mediaFormat": "---",
            "mediaState": "OPENED",
            "mediaStream": "audioRx",
            "mediaType": "AUDIO"
          }
    ]
    """

def parse_json_data(json_data):

    my_list = ["audioRx", "audioTx", "videoRx", "videoTx"]
    channel_types = [media_channel['mediaStream'] for media_channel in json_data]

    for channel_type in my_list:
        if not any(channel_type in x for x in channel_types):
            print("{0} is not in the list".format(channel_type))

json_data = json.loads(json_str)
parse_json_data(json_data)

<强>输出:

videoRx is not in the list
videoTx is not in the list