[英]Python - Proper syntax for 1 line if-else satement
To preface this, I'm very new to programming so bear with me.作为序言,我对编程很陌生,所以请耐心等待。
I'm having issues with the syntax for a function I'm writing where I want it to check for duplicate values within a textfile that's been imported and sorted.我在编写 function 的语法时遇到问题,我希望它检查已导入和排序的文本文件中的重复值。 I want to do this with the following code:
我想用下面的代码做到这一点:
def kollaDublett(dataList):
c = Counter(dataList)
result = [x for x, v in c.items() if v > 1]
dataList is the list I'm checking for duplicates, and I'd like to somehow embedd an if-else
to return either a True or False where result
is defined. dataList 是我正在检查重复项的列表,我想以某种方式嵌入一个
if-else
以返回定义result
的 True 或 False。 The instructor for this assignment said it was possible to do in a single line but she couldn't really make it work since she doesn't have that much experience in Python.这项任务的指导员说可以单行完成,但她无法真正完成,因为她在 Python 方面没有太多经验。
I can return result
and print its value and it'll show the duplicate, but as I mentioned I would like it to check if there's a duplicate then depending on that returning either a True or False.我可以返回
result
并打印它的值,它会显示重复项,但正如我所提到的,我希望它检查是否存在重复项,然后取决于返回 True 或 False。
Thanks in advance!提前致谢!
Specific to your problem, using any
, you could write:针对您的问题,使用
any
,您可以编写:
def kollaDublett(dataList):
c = Counter(dataList)
return any((x for x,v in c.items() if v > 1))
Generally answering your title question about "1 line if-else
statement", you might want to look into ternary operator .通常回答关于“1 line
if-else
statement”的标题问题,您可能需要查看三元运算符。
If you want only a True/False list, you can use a list comprehension:如果您只想要一个 True/False 列表,您可以使用列表推导:
def kollaDublett(dataList):
c = Counter(dataList)
result = [True if v > 1 else False for x, v in c.items()]
return result
Instead, to return a dictionary (expression:duplicate or not):相反,要返回字典(表达式:是否重复):
def kollaDublett(dataList):
c = Counter(dataList)
result = {x:(True if v > 1 else False) for x, v in c.items()}
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.