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. 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. 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.
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.
Thanks in advance!
Specific to your problem, using any
, you could write:
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 .
If you want only a True/False list, you can use a list comprehension:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.