python - 仅当字符串匹配时才在 python 中连接字符串

标签 python python-3.x list dictionary

我有一个像这样的列表中的名字列表

names = ['Test', 'Test 2', 'Test 3', 'Unknown']

我通过执行以下操作将它们从列表转换为字符串:

test = ', '.join(names)

我想加入列表,但如果名称未知,我想忽略。

我怎样才能高效地完成这项工作?

我可以这样做,但这可能不是最好的方法,因为我循环了两次:

arr = []
   for n in names:
      if n != 'Unknown':
         arr.append(n)

最佳答案

您可以使用以下列表理解:

', '.join([i for i in names if i!='Unknown'])
# 'Test, Test 2, Test 3'

关于python - 仅当字符串匹配时才在 python 中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605338/

相关文章:

java.util.List subList(int,int) 在 ArrayList 和 LinkedList 中的行为

python - matplotlib 和 unicode 字符

python - Numpy:获取数组中的最小值索引,忽略特定值

python - 使用 ElementTree 和 BeautifulSoup 解析文件 : is there a way to parse the file by number of tag levels?

python - 如何使用 Pandas 替换列中的元素

python - 将行列表拆分为二维数组

c++ - 子类对象列表重新解释为基类对象列表? (C++11)

javascript - 如何使用 Selenium 和 Python 将文本插入到 div 节点中

python - 在 __init__.py 和 'import as' 语句中导入

python - 如何编写 GRPC python 单元测试