美文网首页Pythonpython
Python基础代码,字典与图片保存

Python基础代码,字典与图片保存

作者: c4a1d989518e | 来源:发表于2017-06-02 10:23 被阅读174次

1.python如何把两个字典像这样相加?

比如一个是 a:1 b:2
另一个是a:2 c:3
相加后得到的新字典是 a:1 b:2 c:3
就是说如果原字典有这个key,就不要加进来了

好像没那么复杂啦,一行代码就搞定了!

{**d2, **d1} #so pythonic!

结果截图:

2.python中如何比较简单的把一个列表按指定数目分成多个列表?

比如[1,2,3,4,5,6,7,8,9,10]分成[1,2,3][4,5,6][7,8,9][10]

给出一种方法:

def list_of_groups(init_list, childern_list_len):
    list_of_groups = zip(*(iter(init_list),) *childern_list_len)
    end_list = [list(i) for i in list_of_groups]
    count = len(init_list) % childern_list_len
    end_list.append(init_list[-count:]) if count !=0 else end_list
    return end_list

可以对任意数组任意分割!

3.python中读取字符串中特定一些字符的问题?

问题是这样的:
比如说我有一个字符串,记事本里面打开看到的是:
0x0000 aa
0x0001 abc
0x0003 abcde
那么我想获取并输出每一行最前面六个字符就可以用readline()再配合一个循环就能做到了。
但是现在如果把这一串字符赋值到一个string变量里,就应该差不多是这样:str="0x0000 aa \n0x0001 abc \n0x0003 abcde"
请问有什么方法可以直接从str里面获取我所需要的字符串,而不通过对文件进行操作?

首先这是一个很基础的问题,方法有很多种。这里给出一种处理方法

with open('./data.txt', 'r') as fp:
    data = fp.read()
[i for i in data.split() if i.startswith('0x')]

结果显示:

4.python如何对excel表格指定内容查找?

如何对excel表格,根据指定名字和指定项目进行查找数据,例如,查找李三的语文成绩,请教大虾,谢谢。

谢邀!看代码

import pandas as pd 
data = pd.read_excel('./test.xlsx') 
data[data.姓名 == '张三'].语文 

这样就可以了。


也可以有这种写法

import pandas as pd 
data = pd.read_excel('./test.xlsx', index_col='姓名') 
# 现在查询成绩就可以写成如下风格,如查询李四语文成绩
data.loc['李四', '语文'] 

如果想把 读取到的张三的语文成绩修改到李四的数学那 只需要如下操作

data.loc['李四', '数学'] = data.loc['张三', '语文']

5.python3.X 如何将list里满足条件的元素与前一个元素合并并将满足条件的元素删除?

List = [aa,1a,1b,bb,bb1,1a,1c,cc,c2,2c,1ac]
现在想将list里以1开头的元素加到前一个元素,并将此元素删除。即列表变为:
List =[aa1a1b,bb,bb11a1c,cc,c2,2c1ac]

直接上代码

list_ = ['aa', '1a', '1b', 'bb', 'bb1',
         '1a', '1c', 'cc', 'c2', '2c', '1ac']

def func(list_):
    for j, i in enumerate(list_):
        if i.startswith('1', 0):
            list_[j-1] += list_[j]
            del list_[j]
    if any([i.startswith('1', 0) for i in list_]):
        list_ = func(list_)
    return list_

6.python 如何处理提取嵌套中括号 [] 的内容?

import re 
b = "[[1,2,344],[323,3,34]]"

regex1 = re.compile(r'\[\[(.*)\]\]')
print (regex1.findall(b))

提取括号内的数字,保存顺序不变。

"""方法一"""

str_ = "[[1,2,344],[323,3,34]]"
list_ = eval(str_)
[i for k in list_ for i in k]

""""方法二"""

import re
string = "[[1,2,344],[323,3,34]]"
regex = re.compile('\d+')
[int(i) for i in re.findall(regex, string)]

7.有关python的一道题,求alice出现了多少次以及最长单词?

回答:
方法一:

import re

max_len = 0
max_len_word = None
with open('./input.txt', 'r') as r_fp:
    string = r_fp.read()
    str_ = re.findall('\w+', str.lower(string))
    word_set = sorted(list(set(str_)))
    with open('./result.txt', 'w') as w_fp:
        for word in word_set:
            number = re.search('\d', word)
            not_str = re.search('\W', word)
            if not number and not not_str:
                w_fp.write(word + ' : ' + str(str_.count(word)) + '\n')
                if len(word) > max_len:
                    max_len = len(word)
                    max_len_word = word
print("max_len_word: {0} \n max_len: {1}".format(max_len_word, max_len))

这里解释一下为什么会有差异,原因是我的《爱丽丝历险记》是随便从网上下载的。alice这个词出现了282次

方法二:

import re
import numpy as np
from collections import Counter
# def statistic_fun2():
with open('./input.txt', 'r') as fp:
    string = fp.read()
    str_ = re.findall('\w+', str.lower(string))

list_ = Counter(str_)
max_index = np.argmax([len(i) for i in list_.keys()])
max_len_word = list(list_.keys())[max_index]
alice_count = list_.get('alice')
print("max_len_word: {0} \n alice_count: {1}".format(max_len_word, alice_count))

两种方法的性能比较:

8.Python中如何把两个list合并,并按从小到大顺序排列?

如题
要用while loop做,不能用sort
谢谢!

a = [1, 3, 2, 78, 32]
b = [23, 32, 12, 78, 65]

def quick_sort(alist):

    if alist == []:
        return []
    else:
        pivot = alist[0]
        lesser = quick_sort([x for x in alist[1:] if x <= pivot])
        greater = quick_sort([x for x in alist[1:] if x > pivot])

    return lesser + [pivot] + greater

quick_sort(a+b)

9.如何用Python读取json文件中的元组?

比如我现在有一个这样的JSON文件
{
a:1,
b:2,

c:[{aa:11,bb:12,cc:13}]
}
我想遍历文件中所有的key/value对,要怎么获得这些数组长度等元素,求好心的大神指点

首先我想说题主举得例子并不是标准json格式,我来举个例子吧


10.Python 有什么奇技淫巧?

奇技淫巧倒算不上,有些时候确实是挺有用的!
list_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
把list_合并为[1, 2, 3, 4, 5, 6, 7, 8, 9]

[k for i in list_ for k in i]

11.爬虫怎么保存图片?

我已经爬到了http.xxxx.jpg这样的连接
但是不知道怎么保存到本地

import requests
for i, j in enumerate(imgUrlList):
    with open('E:/{0}.jpg'.format(i), 'wb') as file:
        file.write(requests.get(j).content)

用with进行上下文管理不需要人为的关闭文件,一旦程序退出with模块文件会自动关闭。本地地址可以随便换,这里用的是requests库如果没有安装直接命令行安装:

pip3 install requests

enumerate函数的功能简单解释,例如:

list_ = ['a', 'b', 'c']
for i, j in enumerate(list_):
    print([i, j])

输出结果为:

[0, 'a']
[1, 'b']
[2, 'c']

在这里 i 迭代的是list_的索引值,j 迭代的是元素值!

文章整理自杨航锋在知乎上的回答

相关文章

网友评论

    本文标题:Python基础代码,字典与图片保存

    本文链接:https://www.haomeiwen.com/subject/mriyfxtx.html