小编qua*_*ana的帖子

Python:为什么附加到列表会产生相同的值

这是我的代码:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
Run Code Online (Sandbox Code Playgroud)

结果是:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]] 
Run Code Online (Sandbox Code Playgroud)

但我希望结果是:

[[0], [0, 1], [0, 1, 2]]
Run Code Online (Sandbox Code Playgroud)

我知道解决方案是使用浅拷贝:res.append(a[:]). 但是有人能告诉我为什么吗?

python

0
推荐指数
1
解决办法
1766
查看次数

BeautifulSoup不能向我显示网站的内容吗?

我想使用名为BeautifulSoup的库来抓取网站的内容。

码:

from bs4 import BeautifulSoup
from urllib.request import urlopen
html_http_response = urlopen("http://www.airlinequality.com/airport-reviews/jeddah-airport/")
data = html_http_response.read()
soup = BeautifulSoup(data, "html.parser")
print(soup.prettify())
Run Code Online (Sandbox Code Playgroud)

输出:

<html style="height:100%">
 <head>
  <meta content="NOINDEX, NOFOLLOW" name="ROBOTS"/>
  <meta content="telephone=no" name="format-detection"/>
  <meta content="initial-scale=1.0" name="viewport"/>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
 </head>
 <body style="margin:0px;height:100%">
  <iframe frameborder="0" height="100%" marginheight="0px" marginwidth="0px" src="/_Incapsula_Resource?CWUDNSAI=9&amp;xinfo=9-57435048-0%200NNN%20RT%281512733380259%202%29%20q%280%20-1%20-1%20-1%29%20r%280%20-1%29%20B12%284%2c315%2c0%29%20U19&amp;incident_id=466002040110357581-305794245507288265&amp;edet=12&amp;cinfo=04000000" width="100%">
   Request unsuccessful. Incapsula incident ID: 466002040110357581-305794245507288265
  </iframe>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

从浏览器检查内容时,主体包含iFrame balise,而不是显示的内容。

python beautifulsoup web-scraping

0
推荐指数
1
解决办法
932
查看次数

如何在 Python3 的一行中获取 string 和 int 作为输入?

我已经看到了以下链接以获得我的答案,但仍然没有得到预期的答案。

如果我在一行中提供 Name 和 Number,Python 应该将第一个值作为字符串,第二个作为整数。

python string integer input python-3.x

0
推荐指数
1
解决办法
1214
查看次数

为什么我的函数在我明确定义它做其他事情时返回 None ?这是计算形状面积的基本函数

我目前正在为我的计算机科学入门课程编写一个简短的程序,尽管我很确定我的定义很明确,但我的代码返回“none”。不要介意我的函数和东西的笨重命名,这是课程要求。代码的目的是可以选择一个形状,然后直接输入需要的信息,不需要书面提示,然后程序会返回选择的形状的面积。在过去的几个小时里,我一直在为此折腾,玩弄它,但无论我做什么,我的代码都没有返回。有什么建议吗?请不要公然给我新代码,因为我可能会因此而惹上麻烦,也许只是指出我的问题方向。

import math

# the following functions are built to calculate each shape

def circle_area(rad):
    return math.pi*rad**2

def rectangle_area(side_one, side_two):
    return side_one*side_two

def triangle_area(edge):
    return (math.sqrt(3)/4)*(edge**2)

# the following function as assigned using the above functions

def shape_area():

    shape_choice = input("Choose shape (1=circle, 2=rectangle, 3=triangle):")

    if shape_choice == 1 or 3:
        length_one = input("")

    elif shape_choice == 2:
        length_two, length_three = input("")

    if shape_choice == 1:
        circle_area(length_one)

    elif shape_choice == 2:
        rectangle_area(length_two, length_three)

    elif shape_choice == 3:
        triangle_area(length_one)

    elif shape_choice …
Run Code Online (Sandbox Code Playgroud)

python math python-3.x

0
推荐指数
1
解决办法
51
查看次数

如何使用列表元素?| PYTHON

我有一个清单,例如['exa', 'mp', 'l', 'e']

我需要使用每个元素来对其进行十六进制化。我想怎么做?首先,我想以某种方式获取每个元素,然后执行 hex(element)。我如何得到它?或者我可以对整个列表进行十六进制化?

提前致谢。

我想说我尝试过str(listname),但它只是输出"['exa', 'mp', 'l', 'e']"不符合我的期望。

python arrays encoding hex list

0
推荐指数
1
解决办法
44
查看次数

在python中热将一个字典中的值添加到另一个字典中

我有两本词典。

Dict1={'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
Dict2={'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}
Run Code Online (Sandbox Code Playgroud)

我想从 Dict1 中获取所有键值对,并在第二个字典中找到相应的股票价格。然后我想在第一个字典中添加股票价格数据。你能帮我解决Python中的问题吗?

我想要的输出是:

Dict3={'comp1':{'Company name':'aaa','Industry':'aaa','Stock price':100},'comp2':{'Company name':'bbb','Industry':'bbb','Stock price':200}}
Run Code Online (Sandbox Code Playgroud)

python dictionary

0
推荐指数
1
解决办法
76
查看次数

如何检查多个字典中的值?

如果我有:

d = {'a': 1, 'b': 3}
e = {'a': 2, 'b': 6}
f = {'a': 1, 'b': 4}
Run Code Online (Sandbox Code Playgroud)

如何检查'b'所有字典中键的值是否大于 2,然后执行函数?

我努力了:

dicts = [d, e, f]
for i in dicts:
    if i['b'] >= 3:
        func()
Run Code Online (Sandbox Code Playgroud)

但是,这会调用该函数 3 次,而我只想在满足所有参数后调用它。

python

0
推荐指数
1
解决办法
57
查看次数

如何使数据类哈希与字符串相同?

我想用 a 替换代码中字典中的字符串键,dataclass以便我可以为键提供元数据以进行调试。但是,我仍然希望能够使用字符串来查找字典。我尝试使用替换函数实现数据类__hash__,但是我的代码未按预期工作:

from dataclasses import dataclass

@dataclass(eq=True, frozen=True)
class Key:
    name: str

    def __hash__(self):
        return hash(self.name)

k = "foo"
foo = Key(name=k)

d = {}
d[foo] = 1

print(d[k])  # Key Error
Run Code Online (Sandbox Code Playgroud)

这两个哈希函数是相同的:

print(hash(k) == hash(foo))  # True
Run Code Online (Sandbox Code Playgroud)

所以我不明白为什么这不起作用。

python hash dictionary python-dataclasses

0
推荐指数
1
解决办法
129
查看次数

为什么函数有时在python中不起作用?

import time

def taym():
    time.sleep(5)

def getprice():
    myfile = open('C:\\Users\\DELL\\Desktop\\Python\\html1.html')
    txt = myfile.read()
    t = txt.find("$")
    it = float(txt[t-4:t])

it=8
while it != 1000:
    getprice()
    if it <= 4.74:
        print("Price is Ok!")
        taym()
    else: 
        print("The price of the coffee beans is "+txt[t-4:t+1])
        taym()
Run Code Online (Sandbox Code Playgroud)

当我在python3中运行此代码时,我收到如下错误消息:

"print("The price of the coffee beans is "+txt[t-4:t+1])
NameError: name 'txt' is not defined."
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用getprice()循环内部的原始代码,但是当我有一个我调用的函数时,我需要知道为什么它不起作用.

python variables file function text-files

-1
推荐指数
1
解决办法
188
查看次数

内联分配 if else 在 Python 中引发错误

我正在做一些验证,写起来会很方便(Pythonic?)

my_variable = value if condition else raise ValueError('Bla bla bla')
Run Code Online (Sandbox Code Playgroud)

我已经尝试过但不允许。有什么方法可以做类似的事情并避免更麻烦的“传统方式”?

if condition:
    my_variable = value
else:
    raise ValueError('Bla bla bla')
Run Code Online (Sandbox Code Playgroud)

python

-1
推荐指数
1
解决办法
47
查看次数