将列表解压缩为字典中的键 - Python 3.4

时间:2015-08-10 02:03:52

标签: python dictionary

我试图对从列表的索引中提取的两个值进行排序,以便字典中的键总是一对值(x,y),使得x<收率

鉴于,例如:

a = [['0', '1', '.5'], ['3', '1', '.7'], ['18','16','.4']]

我想d [(16,18)] = .4,键中的所有数字按从小到大的顺序变为整数,值为浮点数。

以下是我尝试的内容:

a = [['0', '1', '.5'], ['3', '1', '.7'], ['18','16','.4']]

d = {}
for i in a:
    b = sorted([int(i[0]), int(i[1])])
    d[*b] = float(i[2])

我读到了关于解压缩列表here的信息并且认为我已经试一试,但是我在星号上得到了一个SyntaxEror。救命?

3 个答案:

答案 0 :(得分:3)

您可以使用元组作为dict的索引,但它不是参数,因此星号语法不适用:

Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command. 
The EXPIRE family of commands is able to associate an expire to a given key, at the cost of some additional memory used by the key. When a key has an expire set, Redis will make sure to remove the key when the specified amount of time elapsed.

http://redis.io/commands/expire (again)

答案 1 :(得分:2)

正如您所发现的那样,您不能在像这样的索引中使用* -unpacking。但是,如果您使用/* Where a is char * parameter */ memset(a, 0, length + 1); fseek(file, 0, SEEK_SET); fread(a, 1, length, file); 代替tuple(b),我们的代码应该有效(我们无法使用*b本身,因为列表不可以播放,因此无法使用用作字典键。)

b

答案 2 :(得分:1)

这个怎么样?

vars:
  my_rules:
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 1.2.3.4/32
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 2.3.4.5/32

tasks:
  - ec2_group:
      name: security-group-name
     description: Security group description
      vpc_id: vpc-1234567
      region: us-east-1
      profile: profile-name
      purge_rules: true
      rules: my_rules