使用带有值列表的键从字典中获取值的平均值

时间:2016-10-19 14:57:22

标签: python list python-2.7 dictionary jupyter-notebook

对于我在大学的最后一次python任务,我需要在Jupyter Notebook中创建函数来进行一项小型研究。我需要从.csv文件创建字典和列表,并为我从read_csv()函数中获取的字典构建函数。对于这项任务,我可以提问和谷歌,因为我必须做的功能是人们常常遇到的问题。

read_csv()返回后,这些词典的样子如下:

data_dict = { "abc" : [1, 2, 3, 4],
              "def" : [4, 5, 6, 7],
              "ghi" : [8, 9, 10, 11]
            }

所以基本上是一个包含大量键的字典,每个键都有一个值列表。我需要做的是总结每个列表的第一个索引的所有数字,并从总和得到平均值,然后得到第二个索引,第三个索引等等,返回所有平均值的列表。结果如下:

averages = [4.333, 5.333, 6.333, 7.333]

如果不进口任何东西,怎么会这样呢?在过去的几周里,我们还没有真正谈论过使用字典,我曾尝试在互联网上寻找解决方案,但是却找不到任何处理在不同列表中的特定索引上总结整数或浮点数。

3 个答案:

答案 0 :(得分:2)

首先收集值,转置它们然后轻松:

# values of the dict
values = data_dict.values()

# transposed average
averages = [sum(x)/float(len(x)) for x in zip(*values)]
print (averages)

返回:

[4.333333333333333, 5.333333333333333, 6.333333333333333, 7.333333333333333]

较短的'解释性不足的单行内容将是:

averages = [sum(x)/float(len(x)) for x in zip(*data_dict.values())]

答案 1 :(得分:0)

-- target table CREATE TABLE data ( id SERIAL PRIMARY KEY , batch_name varchar NOT NULL , remote_key varchar NOT NULL , payload varchar , UNIQUE (batch_name, remote_key) -- or:: -- , UNIQUE (remote_key) ); -- temp table CREATE TEMP TABLE temp_data ( remote_key varchar -- PRIMARY KEY , payload varchar ); COPY temp_data(remote_key,payload) FROM '/tmp/Account-005' ; -- The actual insert -- (you could also filter out or handle duplicates here) INSERT INTO data(batch_name, remote_key, payload) SELECT 'Account-005', t.remote_key, t.payload FROM temp_data t ; 获取列的值,并将每列的public class SplashScreen extends Acivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //When Notification is tapped if (getIntent().getExtras() != null) { //init message String message = String.valueOf(getIntent().getExtras().get("message")); String title = String.valueOf(getIntent().getExtras().get("title")); //save the message MySharedPreference.save(getApplicationContext() , "message" , message); MySharedPreference.save(getApplicationContext() , "title" , title); startActivity(new Intent(getApplicationContext() , ChatActivity.class)); finish(); } 除以public final class MySharedPreference { public static void save(Context context ,String key , String value){ SharedPreferences prefs= context.getSharedPreferences(YOUR_PACKAGE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor= prefs.edit(); editor.putString(key,value); editor.apply(); } public static String getValue(Context context ,String key){ //if 1st time , register the user SharedPreferences prefs = context.getSharedPreferences(YOUR_PACKAGE_NAME, Context.MODE_PRIVATE); return prefs.getString(key , ""); }

答案 2 :(得分:0)

一种方法可能是:

data_dict = { "abc" : [1, 2, 3, 4],
              "def" : [4, 5, 6, 7],
              "ghi" : [8, 9, 10, 11]
            }
l1 = data_dict.values()
l2 = []
for i in zip(*l1):
    l2.append(float(sum(i)) / float(len(i)))
print l2
相关问题