简体   繁体   中英

Partition list of tuples based on a value within each tuple

I am trying to sort a set of data in to 2 separate lists, fulltime and parttime. But it doesn't seem to be working. Can somebody point to where I'm getting this wrong?

data = [(['Andrew'], ['FullTime'], [38]), 
       (['Fred'], ['PartTime'], [24]), 
       (['Chris'], ['FullTime'], [38])]

def sort(var1, datadump):
    positionlist = []
    for b in range(0, len(datadump)):
        temp2 = datadump[b][1]
        if (temp2 == var1):
            positionlist.append(datadump[b])
    return (positionlist)

FullTimeList = sort("FullTime", data) 
PartTimeList = sort("PartTime", data)

print(FullTimeList) 
print(PartTimeList)

This is solved by altering

if (temp2 == var1):

to

if (temp2[0] == var1):

This is because the elements within each tuple are lists holding a string, not the strings themselves.

This problem could also be solved using two list comprehensions:

FullTimeList = [x for x in data if x[1][0] == 'FullTime']
PartTimeList = [x for x in data if x[1][0] == 'PartTime']

Not an answer: just a suggestion. Learn how to use the python debugger.

python -m pdb <pythonscript.py>

In this case, set a breakpoint on line 9

b 9

Run the program

c

When it breaks, look at temp2

p temp2

It tells you

['FullTime']

Look at var1

p var1

It tells you

'FullTime'

And there is your problem.

You'll get a better understanding if you name your variables and functions with descriptive names:

data = [(['Andrew'], ['FullTime'], [38]), 
        (['Fred'], ['PartTime'], [24]), 
        (['Chris'], ['FullTime'], [38])]

def filter_records(value, records):
    result = []

    for i in range(len(records)):  # i and j are usual variable names for indices (b is not)
        record = records[i]
        name, work, hours = record   # give names to the parts 
        if work[0] == value:         # work[0] since the values are lists (no need for parenthesis)
            result.append(record)
    return result                    # no need for parenthesis

FullTimeList = filter_records("FullTime", data) 
PartTimeList = filter_records("PartTime", data)

the pattern:

for i in range(len(records)):
    record = records[i]

is an anti-pattern in Python - meaning that there is a better way to write it:

for record in records:
    ...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM