我有一个位置名称,然后是每个位置的纬度和经度.我正在尝试确定在Python中用两个值表达单个键的最佳方法.我在想这个:
dict = {
'California': ('36.46715833333333', '-117.85891388888888'),
'California2': ('36.46715833333333', '-117.85891388888888'),
}
Run Code Online (Sandbox Code Playgroud)
然后添加更多:
dict['California'] = ('36.46715833333333', '-117.85891388888888')
Run Code Online (Sandbox Code Playgroud)
但是,我将如何轻松地遍历每个并提取它们?
for location in dict:
for lat, lon in location:
print lat, lon
Run Code Online (Sandbox Code Playgroud)
这给出了一个ValueError,声明它没有多个值可以解压缩.我如何迭代这个并得到每个lat和long?
我想知道哪种是从相同类型的对象列表中获取属性的最佳方法.有没有比for循环更有效的解决方案?我尝试使用getattr,但没有使用列表.
只是为了说清楚.假设我已经定义了一个带有属性的类FooBar
class Foo():
def __init__(self, Bar):
self.bar = Bar
A = Foo(5)
B = Foo(6)
C = [A,B]
Run Code Online (Sandbox Code Playgroud)
我是否可以Bar为整个列表同时获取属性以使最终结果为值为[5,6]的列表?谢谢你的帮助
我有以下等式:
result=[(i,j,k) for i in S for j in S for k in S if sum([i,j,k])==0]
Run Code Online (Sandbox Code Playgroud)
我想在if语句中添加另一个条件,使得我的结果集不包含(0,0,0).我尝试执行以下操作:
result=[(i,j,k) for i in S for j in S for k in S if sum([i,j,k])==0 && (i,j,k)!=(0,0,0)]但是我收到指向的语法错误&&.我测试了我的表达式第一个条件并且它是正确的.
我试图从这个维基百科页面刮掉有生日的人
这是现有的代码:
hdr = {'User-Agent': 'Mozilla/5.0'}
site = "http://en.wikipedia.org/wiki/"+"january"+"_"+"1"
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
print soup
Run Code Online (Sandbox Code Playgroud)
这一切都很好,我得到整个HTML页面,但我想要特定的数据,我不知道如何使用没有id使用的Beautiful Soup访问它.该<ul>标签没有一个id也不做<li>标记.另外,我不能只询问每个<li>标签,因为页面上还有其他列表.是否有特定方式来调用给定列表?(我不能只为这一页使用修复程序,因为我计划迭代所有日期并让每个页面生日,我不能保证每个页面都与此页面完全相同).
我想在继续之前创建需要用户输入大于2的整数的代码.我正在使用python 3.3.这是我到目前为止所拥有的:
def is_integer(x):
try:
int(x)
return False
except ValueError:
print('Please enter an integer above 2')
return True
maximum_number_input = input("Maximum Number: ")
while is_integer(maximum_number_input):
maximum_number_input = input("Maximum Number: ")
print('You have successfully entered a valid number')
Run Code Online (Sandbox Code Playgroud)
我不确定的是如何最好地处理整数必须大于2的条件.我刚刚开始学习python但是想要养成良好的习惯.
我有一个带有单个数值的条目的嵌套列表,我需要确定哪个值总共有更高的外观百分比.
[['3', '7', '13', '4'],
['7', '3', '2', '1', '13', '4'],
['3', '13'],
['3', '7', '4', '13'],
['7', '3', '13', '4'],
['3', '13', '7', '8', '4'],
['1', '7', '3', '4', '13'],
['13'],
['7', '3', '13'],
['7', '3', '4']]
Run Code Online (Sandbox Code Playgroud)
在此示例中,数字"13"出现在90%的条目中.
我知道我可以迭代每个条目,使用计数器并在结尾比较结果,但应该有一个更简洁的方法来做到这一点.
有什么帮助吗?
提前致谢.
我对python很新,我想知道是否有一种编辑范围(100)的方法,以便它取出所有奇数?我正在尝试制作一个简单的"游戏",你想到一个数字,它告诉你做一些简单的数学,然后告诉你剩下的是什么数字,并且它现在完美地工作,除非它返回一个奇数你最后留下了.5(不是一个主要的问题,但我宁愿把它删除,以使它更简单).这就是我现在所拥有的:
import random, time
numList = range(100)
def getRandomNumber(numList):
numIndex = random.randint(0, len(numList) - 1)
return numList[numIndex]
def restartProg():
print('Do you want to restart? (Y/N)')
return input().lower().startswith('y')
secretNumber = getRandomNumber(numList)
secretNumber = str(secretNumber)
answer = int(secretNumber)/2
answer = str(answer)
while True:
print()
print('Think of a number between 1 and 100.')
time.sleep(3)
print()
print('Now double that number.')
time.sleep(3)
print()
print('Add ' + secretNumber + ' to it.')
time.sleep(6)
print()
print('Now divide it by 2.')
time.sleep(6)
print()
print('And finally, take …Run Code Online (Sandbox Code Playgroud) 我是OS X 10.8上运行2.7.6的Python初学者,添加了numpy和pyobjc.这是我正在尝试运行的脚本:
from __future__ import with_statement
from Foundation import NSMutableDictionary, NSUserDefaults, NSCFArray, objc
import numpy as np
from copy import copy
import os
import re
domainName = "org.mworks-project.MWClient"
outFile = os.path.expanduser(os.path.join('~/Desktop','org.Behavior.MWClientSavedVars.plist'))
keyNames = [
'MATLAB client window - selected variables',
'MATLAB client window - MATLAB .m file',
'recentPythonScripts' ]
homedir = os.getenv('HOME')
################
def subStr(inStr):
return re.sub('^%s'%homedir, '$HOME', inStr)
def replaceUserdirWithStr(inObj):
if type(inObj) == str or type(inObj) == objc.pyobjc_unicode:
return subStr(inObj)
elif isinstance(inObj, NSCFArray):
for i in range(len(inObj)):
# …Run Code Online (Sandbox Code Playgroud) 我正在学习python文件处理.我尝试使用此代码一次读取一个字符
f = open('test.dat', 'r')
while (ch=f.read(1)):
print ch
Run Code Online (Sandbox Code Playgroud)
为什么它不起作用
这是错误消息
C:\Python27\python.exe "C:/Users/X/PycharmProjects/Learning Python/01.py"
File "C:/Users/X/PycharmProjects/Learning Python/01.py", line 4
while (ch=f.read(1)):
^
SyntaxError: invalid syntax
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud) 我是 Python 新手,并且一直坚持打印由分隔符分隔的数组元素。我的数组由 60 000 奇数行组成,每行 26 个元素,其中一些元素仅包含数字,而其他元素则包含各种字符,包括特殊字符。例子:
a[0] = [abc,123,a1b2c3,*wewqe,...]
a[1] = [098i,qwerty,123qwe,xx-u,...]
Run Code Online (Sandbox Code Playgroud)
我希望输出是(最后一个元素后面没有“|”并且每一行都在自己的行上:
abc|123|a1b2c3|*wewqe,...
098i|qwerty|123qwe|xx-u,...
Run Code Online (Sandbox Code Playgroud)
我已尝试以下方法,但它们不起作用:
for row in results :
length = len(row)
print("")#throw in a new line
print ("Number of elements: " + str(length))
print '|'.join((str(row)))
Run Code Online (Sandbox Code Playgroud)
和这个:
for row in results :
length = len(row)
print("")#throw in a new line
print ("Number of elements: " + str(length))
for item in row:
print '|'.join(str(item))
Run Code Online (Sandbox Code Playgroud)
和这个:
for row in results :
length = len(row)
print("")#throw in a new …Run Code Online (Sandbox Code Playgroud) python ×10
python-2.7 ×2
python-3.x ×2
arrays ×1
class ×1
exception ×1
html-parsing ×1
if-statement ×1
input ×1
list ×1
python-3.3 ×1
range ×1
validation ×1
web-scraping ×1