首页 > 解决方案 > How can I condence this function into returning a value from a list comprehension?

问题描述

I understand it may not be best practices or conventional but this is more of a personal challenge.

def initialize_dataset(source):
    all_features = []
    targets = []
    for (sent, label) in source:
        feature_list=[]
        feature_list.append(avg_number_chars(sent))
        feature_list.append(number_words(sent))
        all_features.append(feature_list)
        targets.append(0) if label=="austen" else targets.append(1)
    return all_features, targets

Example of what I'm looking for. I understand that it might not be possible to get it down to one single list and or value. But something close to it. I'd like to kind of expand my thinking on writing list comprehensions.

def sample_function(data):
    return [i for i in data ]

标签: python-3.xlist-comprehension

解决方案


成功!我的 gaaaaaaaaaaaaaaawd 太丑了!

def initialize_dataset(source):
    all_features, targets = [],[]; [(all_features.append([avg_number_chars(sent), number_words(sent)]), targets.append(0) if label == "austen" else targets.append(1)) for (sent, label) in source]; return all_features, targets

推荐阅读