Dict理解提示

时间:2015-10-07 14:37:34

标签: python dictionary

我开始使用列表推导,我在语法上有点迷失,我怎么能把它翻译成dict comprehensions:

dict_users ={user: count for user in wut count = 0 for line in lines if user in lines}

我尝试了不同的变化,但我一直都弄错了。

public class TestService extends Service {

ActivityManager am = null;
private TimerTask mTask;
private Timer mTimer;

public TestService() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.v("TestService", "onStartCommand");

    am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

    mTimer = new Timer();
    initializeTimerTask();
    mTimer.schedule(mTask, 1, 500);

    return 0;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

private void initializeTimerTask(){
    mTask = new TimerTask() {
        @Override
        public void run() {
            List<ActivityManager.RunningAppProcessInfo> taskInfo = am.getRunningAppProcesses();
            String currentRunningActivityName = taskInfo.get(0).processName;

            Log.v("TestService", "" + currentRunningActivityName);


        }
    };
}

3 个答案:

答案 0 :(得分:4)

您无法在生成器表达式/列表或字典理解中指定(count = 0count += 1),您需要使用sum代替此类事物。我想你想要的是:

dict_users = {user: sum(user in line for line in lines) for user in wut }

请注意,这会使用True'f' in 'foo')和False'f' in 'bar')分别评估为10的事实总而言之,因为布尔值是整数子类。一个简单的例子:

>>> lines = ['foo', 'bar', 'baz']
>>> users = ['ba', 'f']
>>> {user: sum(user in line for line in lines) for user in users}
{'ba': 2, 'f': 1}

但是这可以说比你现在拥有的嵌套for循环更不易读。

答案 1 :(得分:2)

Counter已为您计算物品;你只需要一个合适的行序列作为参数传递。

dictUsers = Counter(line for user in wut for line in lines if user in line)

生成器表达式中的for子句与等效嵌套for循环的顺序相同。

答案 2 :(得分:1)

实际上我最近读了一篇博文,相当好地解释了嵌套的理解,虽然我不记得这个链接。扩展jonrsharpe的答案:

for x in list_of_tuples:
    for y in x:
        do(y)

变为:

[do(y) for x in list_of_tuples for y in x]

所以基本上你要击退退格,直到所有for's都在一行上,删除冒号,然后将最终功能移到前面。

请记住,您不能进行任何任务,仅适用于最终行动。

无法做到全面:

for x in range(10):
    x = range(x)
    for y in x:
        do(y)

CAN COMPREHEND:

for x in range(10):
    for y in range(x):
        do(y)