我在Python中的List中有一个List,我想使用List comprehension将它们转换为单个列表:
>>> aa = [[1,2],[1,2]]
>>> bb = [num for num in numbers for numbers in aa]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined
>>>
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
*我的问题的答案不是如上所述的副本,它低于这个问题.
我正在尝试编写一个程序,根据项目中的最后一个字符对字符串列表进行排序.
["Tiger 6", "Shark 4", "Cyborg 8"] 我的列表是如何导入的,但我需要根据最后的数字将它们按数字顺序排列.
提前致谢!
我正在学习python.如果有人可以解释以下处理文件之间的差异,是否可能:
file = open("file.txt")
for line in file:
#do something
file = open("file.txt")
contents = file.read()
for line in contents:
# do something
Run Code Online (Sandbox Code Playgroud)
我知道在第一种情况下,文件将作为一个列表,所以我们迭代一个文件,因为我们迭代列表的元素,但在第二种情况下,我不知道如何解释如果我读取文件会发生什么首先然后迭代它?
我看到这里有类似的问题,但没有什么能完全帮助我.我还查看了有关命名空间的官方文档,但找不到任何真正帮助我的文档,也许我只是对XML格式化方面的新手.我明白也许我需要创建自己的命名空间字典?无论哪种方式,这是我的情况:
我从API调用中得到一个结果,它给了我一个XML,它在我的Python应用程序中存储为一个字符串.
我想要完成的只是抓取这个XML,交换一个微小的值(b:字符串值用户ConditionValue/Default但这与此问题无关)然后将其保存为字符串以便稍后在Rest POST中发送呼叫.
源XML看起来像这样:
<Context xmlns="http://Test.the.Sdk/2010/07" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<xmlns i:nil="true" xmlns="http://schema.test.org/2004/07/Test.Soa.Vocab" xmlns:a="http://schema.test.org/2004/07/System.Xml.Serialize"/>
<Conditions xmlns:a="http://schema.test.org/2004/07/Test.Soa.Vocab">
<a:Condition>
<a:xmlns i:nil="true" xmlns:b="http://schema.test.org/2004/07/System.Xml.Serialize"/>
<Identifier>a23aacaf-9b6b-424f-92bb-5ab71505e3bc</Identifier>
<Name>Code</Name>
<ParameterSelections/>
<ParameterSetCollections/>
<Parameters/>
<Summary i:nil="true"/>
<Instance>25486d6c-36ba-4ab2-9fa6-0dbafbcf0389</Instance>
<ConditionValue>
<ComplexValue i:nil="true"/>
<Text i:nil="true" xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<Default>
<ComplexValue i:nil="true"/>
<Text xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<b:string>NULLCODE</b:string>
</Text>
</Default>
</ConditionValue>
<TypeCode>String</TypeCode>
</a:Condition>
<a:Condition>
<a:xmlns i:nil="true" xmlns:b="http://schema.test.org/2004/07/System.Xml.Serialize"/>
<Identifier>0af860f6-5611-4a23-96dc-eb3863975529</Identifier>
<Name>Content Type</Name>
<ParameterSelections/>
<ParameterSetCollections/>
<Parameters/>
<Summary i:nil="true"/>
<Instance>6364ec20-306a-4cab-aabc-8ec65c0903c9</Instance>
<ConditionValue>
<ComplexValue i:nil="true"/>
<Text i:nil="true" xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<Default>
<ComplexValue i:nil="true"/>
<Text xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<b:string>Standard</b:string>
</Text>
</Default>
</ConditionValue>
<TypeCode>String</TypeCode>
</a:Condition>
</Conditions>
Run Code Online (Sandbox Code Playgroud)
我的工作是交换其中一个值,保留源的整个结构,并使用它在应用程序中稍后提交POST.
我遇到的问题是,当它保存到字符串或文件时,它完全混淆了名称空间:
<ns0:Context xmlns:ns0="http://Test.the.Sdk/2010/07" xmlns:ns1="http://schema.test.org/2004/07/Test.Soa.Vocab" xmlns:ns3="http://schemas.microsoft.com/2003/10/Serialization/Arrays" …Run Code Online (Sandbox Code Playgroud) 我有这个XML字符串结果,我需要获取标签之间的值.但XML的数据类型是字符串.
final = " <Table><Claimable>false</Claimable><MinorRev>80601</MinorRev><Operation>530600 ION MILL</Operation><HTNum>162</HTNum><WaferEC>80318</WaferEC><HolderType>HACARR</HolderType><Job>167187008</Job></Table>
<Table><Claimable>false</Claimable><MinorRev>71115</MinorRev><Operation>530600 ION MILL</Operation><Experiment>6794</Experiment><HTNum>162</HTNum><WaferEC>71105</WaferEC><HolderType>HACARR</HolderType><Job>16799006</Job></Table> "
Run Code Online (Sandbox Code Playgroud)
这是我的代码示例
root = ET.fromstring(final)
print root
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误:
xml.parsers.expat.ExpatError: The markup in the document following the root element must be well-formed.
Run Code Online (Sandbox Code Playgroud)
我尝试过使用ET.fromstring.但没有运气.
假设我有一个字符串"abcdefghijklmnopqrstuvwxyz",我想用这些值初始化字典键.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabetDict = dict()
for char in alphabet:
alphabetDict[char] = 0
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
我有一个类将字典转换为这样的对象
class Dict2obj(dict):
__getattr__= dict.__getitem__
def __init__(self, d):
self.update(**dict((k, self.parse(v))
for k, v in d.iteritems()))
@classmethod
def parse(cls, v):
if isinstance(v, dict):
return cls(v)
elif isinstance(v, list):
return [cls.parse(i) for i in v]
else:
return v
Run Code Online (Sandbox Code Playgroud)
当我尝试制作对象的深层副本时,我收到了此错误
import copy
my_object = Dict2obj(json_data)
copy_object = copy.deepcopy(my_object)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 172, in deepcopy
copier = getattr(x, "__deepcopy__", None)
KeyError: '__deepcopy__'
Run Code Online (Sandbox Code Playgroud)
但是我在类I中重写getattr函数Dict2obj能够进行深层复制操作.见下面的例子
class Dict2obj(dict):
__getattr__= dict.__getitem__
def __init__(self, d):
self.update(**dict((k, self.parse(v))
for k, v in d.iteritems()))
def __getattr__(self, key): …Run Code Online (Sandbox Code Playgroud) 所以我希望它独立于使用代码的计算机,所以我希望能够在当前目录中创建一个目录并将我的绘图保存到该新文件中.我看了一些其他的问题并试了一下(我有两次尝试,一次注释掉):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs')
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
Run Code Online (Sandbox Code Playgroud)
我收到错误:
AttributeError: 'module' object has no attribute 'mkdirs'
Run Code Online (Sandbox Code Playgroud)
我也想知道我在目录中保存它的想法是否有效,我无法测试,因为我在上面的部分中遇到了错误.
我正在尝试导入许多文件。我有一个字符串列表(myList),这些字符串是我要导入的模块文件的名称。我要导入的所有文件都在名为parentDirectory的目录中。该目录位于此代码所在的文件夹中。
到目前为止,我有:
myList = {'fileOne', 'fileTwo', 'fileThree'}
for toImport in myList:
moduleToImport = 'parentDirectory.'+toImport
import moduleToImport
Run Code Online (Sandbox Code Playgroud)
这段代码只是将moduleToImport视为模块的名称,但是我希望代码理解它是字符串的变量。
This is the Error Code:
dule>
import moduleToImport
ImportError: No module named moduleToImport
Run Code Online (Sandbox Code Playgroud) 我有这样的清单
['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']
Run Code Online (Sandbox Code Playgroud)
在python中.我想找到像这样的字符串列表的总和:
['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']
Run Code Online (Sandbox Code Playgroud)
我应该先将它们转换为列表中的列表吗?如果是这样我将如何解决这个问题?
尽力学习如何编写科学代码.
python ×10
list ×2
python-2.7 ×2
string ×2
xml ×2
class ×1
class-method ×1
dictionary ×1
elementtree ×1
for-loop ×1
lxml ×1