我有一个列表"testlist"
,其中包含4个子列表
[
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
我想从“测试列表”中获得以下字典
{group1:[name1,name2], group2:[name3,name4]}
我在这里有这小段代码,它从每个子列表中获取“组”元素,然后使用所获取的元素作为键来更新字典。我坚持的是如何填充这些键的值?
def test():
dic={}
testlist = [
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
for each in testlist:
dic.update{each[3]:[]}
答案 0 :(得分:0)
考虑到// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
每个子列表中的项目都是字符串,请尝试以下方法:
testlist
以下是相同的代码:
dic = {i : [j[0] for j in testlist if i==j[3]] for i in set([k[3] for k in testlist])}
答案 1 :(得分:0)
在列表上使用“传统”循环(假设在某处定义了name1,ip1等):
def test():
dic = {}
testlist = [
[name1, ip1, mask1, group1],
[name2, ip2, mask2, group1],
[name3, ip3, mask3, group2],
[name4, ip4, mask4, group2]
]
for each in testlist:
if each[3] not in dic:
dic[each[3]] = []
dic[each[3]].append(each[0])
return dic