Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回列表中完整字符串的变量_Python - Fatal编程技术网

Python 返回列表中完整字符串的变量

Python 返回列表中完整字符串的变量,python,Python,我有以下代码: topic = "test4" topics = sns.get_all_topics() topicsList = topics['ListTopicsResponse']['ListTopicsResult']['Topics'] topicsListNames = [t['TopicArn'] for t in topicsList] 返回一个列表: [u'arn:aws:sns:us-east-1:10:test4', u'arn:aws:sns:us-east-

我有以下代码:

topic = "test4"
topics = sns.get_all_topics()   
topicsList = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topicsListNames = [t['TopicArn'] for t in topicsList]
返回一个列表:

[u'arn:aws:sns:us-east-1:10:test4', u'arn:aws:sns:us-east-1:11:test7']
我现在尝试的是创建一个变量,它返回与
主题
变量相关的完整字符串

我有一个变量
topic=“test4”
,我想有一个变量
topicResult
,它返回
u'arn:aws:sns:us-east-1:10:test4

主题相关的字符串
并不总是位于列表第一位

你知道怎么做吗

topicResult = " ".join([t['TopicArn'] for t in topicsList if t['TopicArn'].endswith(topic)])
这将检查列表中的字符串,查看
主题
变量是否是其中一个字符串的结尾
“”.join()提供了一个字符串,但如果要保留以
主题
结尾的字符串列表,可以将其删除。如果
topic
不总是在字符串的末尾,您可以检查
topic
是否在字符串中

topicResult = " ".join([t['TopicArn'] for t in topicsList if topic in t['TopicArn']])

您可以使用带有check语句的意图列表,但我认为内置过滤器会更快:

topicsListNames = filter(lambda item: item['TopicArn'].endswith(topic), topicsList)

基本上,此行接受
topicsList
,然后只接受
item['TopicArn']的项目
item
。endswith(topic)
为True,即
'TopicArn'
元素以
topic
变量的引用结尾的项目。最后,返回所有这些“好”项目,并且
topicsListNames
引用它们。

因此您总是希望在
t['TopicArn']中找到项目。endswith(topic)