如何将变量添加到带循环的字典中?

时间:2016-01-22 04:52:14

标签: python loops for-loop dictionary python-3.4

我对python很陌生,我试图创建能够完成我手工完成的所有工作的循环。基本上创建所有行#' 变量,并从文件' game_catch.txt' 中分配特定的文本行。读到这样的东西:

Curving                 10
Dodgeball               15
Keep Away               5
Kin-Ball                7
Prisoner Ball           21
Quidditch               30
Rundown (aka Pickle)    12
Yukigassen              18
Handball                25

(空格为Tabs,如果有任何区别的话)

然后创建另一个循环,在分割时将行' 变量的值分配给 str'#' 变量所有的间距。 (我无法修改该文件,因为在其他计算机中它将与我上面发布的文件相同,所以我必须执行此步骤)

然后,更重要的是因为这是我完全陷入困境的地方,为完成 str'#' 变量的所有细节工作做了一个循环进入体育词典可以拿起的东西,然后读作 {' Curving':10}

在这里,我提供了目前正在使用并尝试简化的代码:

file = open('game_catch.txt','r')
line1 = file.readline()
line2 = file.readline()
line3 = file.readline()
line4 = file.readline()
line5 = file.readline()
line6 = file.readline()
line7 = file.readline()
line8 = file.readline()
line9 = file.readline()

str1 = line1.split()
str2 = line2.split()
str3 = line3.split()
str4 = line4.split()
str5 = line5.split()
str6 = line6.split()
str7 = line7.split()
str8 = line8.split()
str9 = line9.split()

sports = {}

key = ''
for i in str1[0:-1] :
    key += i + ' '

key = key[0:-1]

sports[key] = int(str1[-1])

很抱歉这篇长篇文章,我只想提供尽可能详细的信息。如果有更有效的方法,请随时告诉我。感谢

4 个答案:

答案 0 :(得分:2)

您可以通过迭代文件,分割每一行,并将该生成器中的对发送到@RunWith(PowerMockRunner.class) @PrepareForTest({ LocationAppDAO.class, BeanPropertyRowMapper.class }) public class CopyOfGeoLocationAppTest { @Autowired private ApplicationContext applicationContext; @Test @SuppressWarnings({ "unchecked" }) public void testJdbcTemplateforDbase() throws Exception { // LocationAppDAO locationAppdao= new LocationAppDAO(); String queryWgs84 = "SELECT * FROM location_wgs84 where latitude=" + 0 + " AND longitude=" + 0; LocationAppDAO locationAppDaoMock= EasyMock.createMock(LocationAppDAO.class); JdbcTemplate jdbcTemplateMock = EasyMock.createMock(JdbcTemplate.class); BeanPropertyRowMapper<Location_wgs84> beanPropertyRowMapperMock = EasyMock .createMock(BeanPropertyRowMapper.class); EasyMock.replay(beanPropertyRowMapperMock); // mocking location Location_wgs84 location_wgs84mock = EasyMock .createMock(Location_wgs84.class); location_wgs84mock.setLatitude(0); location_wgs84mock.setLongitude(0); EasyMock.replay(location_wgs84mock); PowerMock.expectNew(BeanPropertyRowMapper.class).andReturn( beanPropertyRowMapperMock); PowerMock.replayAll(); ArrayList<Location_wgs84> arrayList = new ArrayList<Location_wgs84>(); Location_wgs84 location1 = new Location_wgs84(); location1.setLatitude(1); location1.setLongitude(1); arrayList.add(location1); Location_wgs84 location2 = new Location_wgs84(); location2.setLatitude(2); location2.setLongitude(2); arrayList.add(location2); Location_wgs84 location3 = new Location_wgs84(); location3.setLatitude(3); location3.setLongitude(3); arrayList.add(location3); EasyMock.expect( jdbcTemplateMock.query(queryWgs84, beanPropertyRowMapperMock)) .andStubAnswer(new IAnswer<List<Location_wgs84>>() { @Override public List<Location_wgs84> answer() throws Throwable { return arrayList; }; }); EasyMock.replay(jdbcTemplateMock); EasyMock.expect( locationAppDaoMock.location_wgs84Query(0,0)) .andStubAnswer(new IAnswer<List<Location_wgs84>>() { @Override public List<Location_wgs84> answer() throws Throwable { return arrayList; }; }); EasyMock.replay(locationAppDaoMock); LocationAppDAO locationAppdao= new LocationAppDAO(); ReflectionTestUtils.setField(locationAppdao, "jdbcTemplate", jdbcTemplateMock); List<Location_wgs84> arrayListResult = locationAppdao.location_wgs84Query(0, 0); assertEquals(3.0, arrayListResult.get(2).getLatitude(), 0); EasyMock.verify(jdbcTemplateMock); } } 来获得基本结构(将分数保持为字符串):

dict()

您可以通过创建生成器来分割每一行,然后解压每一行并使用with open('game_catch.txt') as f: d = dict(line.rsplit(maxsplit=1) for line in f) 函数来将分数转换为整数:

int()

您可以使用文字理解语法而不是with open('game_catch.txt') as f: d = dict((name, int(score)) for name, score in (line.rsplit(maxsplit=1) for line in f)) 函数:

dict()

当然,最重要的部分是查看教程,以便您可以了解这些代码片段的作用并理解解释。循环和数据结构尤为重要。

答案 1 :(得分:1)

考虑到一些体育名称由多个单词组成,以下内容将把你的txt文件变成字典:

lines = [line.rstrip('\n').split() for line in open('C:/Users/Simon/Desktop/test.txt')]

sports = {}

for el in lines:
    number = el.pop()
    curItem = ' '.join(el)

    sports[curItem] = int(number)

print sports

这将是这样的:

{'Curving': 10, 'Keep Away': 5, 'Dodgeball': 15}

答案 2 :(得分:0)

file = 'game_catch.txt'
sports = {}

with open(file) as f:
 for line in f:
  parts = line.split()
  sports[parts[0]] = int(parts[-1])
希望这会有所帮助。

答案 3 :(得分:0)

示例

trans_dict = {&#39; one&#39;:&#39; wahed&#39;,&#39; two&#39;:&#39; itnen&#39;,&#39; three&#39; :&#39;塔拉塔&#39;}

       print "ITER ITEMS", trans_dict.iteritems()

       for key, val in trans_dict.iteritems():

                   print "KEY", key

                   print "VAL", val