我有两个内容词典:
dct1 = {'NL': 7,'MC': 9, 'PG': 8}
dct2 = {'NL': 2,'MC': 10,'PG': 6}
你可以说这些代表来自游戏的分数,其中字母是名称而数字是分数。两个词典之间的差异是根据标准计算它们的数字。
现在我想将字典中的内容组合成一个列表列表。我将简单地提供我的代码。基本上我当时所做的就是将两个词典中的内容转换为列表列表:
L1 = [['NL',7],['MC',9],['PG',8]]
L2 = [['NL',2],['MC',10],['PG',6]]
将它们转换为列表列表的代码:
L1 = []
for i, occurrences in dct1.items():
L1.append([i,occurrences])
L2 = []
for j, occurrences in dct2.items():
L2.append([j,occurrences])
一旦我打印了两个列表,我就像上面写的一样。
但是现在,我想将两个列表组合成一个列表,而不是列出两个不同的列表:
L3 = [['NL',7,2],['MC',9,10],['PG',8,6]]
基本上,单个列表不必重复两次字母,只需添加第二个数字。非常感谢任何帮助。
答案 0 :(得分:9)
列表理解应该:
lst = [[k, v, dct2[k]] for k, v in dct1.items()]
print lst
# [['NL', 7, 2], ['PG', 8, 6], ['MC', 9, 10]]
请注意,子列表的排序可能会有所不同,因为字典不是有序的。
答案 1 :(得分:1)
因为两个字典中的键都相同:
>>> dct1 = {'NL': 7,'MC': 9, 'PG': 8}
>>> dct2 = {'NL': 2,'MC': 10,'PG': 6}
>>> L3 = []
>>> for key in dct1:
... L3.append([key, dct1[key], dct2[key]])
...
>>> L3
[['NL', 7, 2], ['PG', 8, 6], ['MC', 9, 10]
答案 2 :(得分:0)
您可以使用import py2neo
from py2neo import Graph
from py2neo import Node, Relationship
from py2neo import authenticate
import tweepy
import time
auth = tweepy.OAuthHandler('...', '...')
auth.set_access_token('...', '...')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.get_user(myUser)
def getFollowers(user_screen_name):
follower_ids=[]
for page in tweepy.Cursor(api.followers, screen_name=user_screen_name).pages():
time.sleep(60)
follower_ids.extend(page)
return follower_ids
def getFollowing(user_screen_name):
following_ids=[]
for page in tweepy.Cursor(api.friends, screen_name=user_screen_name).pages():
time.sleep(60)
following_ids.extend(page)
return following_ids
def createNode(screen_name):
node=Node("User", screen_name=screen_name)
gf.merge(node)
return
def createRelationship(nodeA, nodeB, relationship):
#creates relationship and nodes (if not existant)
nodeA=Node("User", screen_name=nodeA)
nodeB=Node("User", screen_name=nodeB)
gf.merge(nodeA)
gf.merge(nodeB)
gf.merge(Relationship(nodeA, relationship, nodeB))
return
authenticate("localhost:7474",myID,myPass)
gf = Graph()
#First time graph is created
gf.run("CREATE CONSTRAINT ON (u:User) ASSERT u.screen_name IS UNIQUE")
createNode(myUser)
user_followers=getFollowers(myUser)
user_following=getFollowing(myUser)
for followers in user_followers:
createRelationship(followers.screen_name, sc, "FOLLOWS")
i=1
for following in user_following:
createRelationship(sc, following.screen_name, "FOLLOWS")
将项目放入列表中。另外,在list comprehension
上使用get()方法,这样如果其他字典中没有键,它就不会抛出键错误。
dict
答案 3 :(得分:0)
Assuming you are using python 2.7.x
了解
L3 = []
for key, value in dct1.iteritems():
L3.append([key, value, dct2[key])
OR
使用列表理解的简短和甜蜜:
L3 = [[key, value, dct2[key]] for key, value in dct1.iteritems()]