【问题标题】:Use two lists to create different sentences使用两个列表创建不同的句子
【发布时间】:2017-01-29 02:16:06
【问题描述】:

所以我有两个列表。假设一个列表包含美国每个州的首府,另一个列表包含该州。显然,这两个列表的排序方式是 list1 中的第一个元素(大写)对应于 list2 的第一个元素(状态)。

当只使用一个列表时,好像我只需要在一句话中改变一件事,我目前使用如下代码:

list = map(str.strip, list(open('list.txt', 'r')))
questions = ['What is the capital of the state %s' %(element) for element in list]

with open('questions.txt', 'w') as fd:
    fd.write("\n".join(questions))

所以在这个例子中,我只使用美国各州的一个列表 (list.txt),通过运行代码,它会输出一个 .txt 文件 (questions.txt),其中包含许多行:

What is the capital of the state California?

以及 list.txt 中的任何状态。

现在,回到我的问题。如前所述,有时我需要在一个句子(或我正在做的任何事情)中使用两个列表,例如:

(first element of list1) is the capital of the US state (first element from list2)
(second element of list1) is the capital of the US state (second element from list2)
(third element of list1) is the capital of the US state (thirdelement from list2)

等等……

但我不确定如何修改上面的代码以包含两个列表而不是一个。

提前致谢。

编辑: List1 示例:

Sacramento
Austin
Phoenix

List2 示例:

California
Texas
Arizona

【问题讨论】:

  • 你能举一个列表的例子和你想要达到的目标吗?
  • 请不要使用list作为变量名。
  • 已更新示例。对不起,我再也不会这样做了:)

标签: python list


【解决方案1】:

您可以使用zip 遍历一对列表:

capitals = tuple(map(str.rstrip, open('capitals.txt')))
states = tuple(map(str.rstrip, open('states.txt')))
answers = ['The capital of {} is {}'.format(state, capital) 
           for state, capital in zip(states, capitals)]

我对您的代码进行了一些简化,并切换到了更新的、推荐的字符串格式化方式。我还用tuple 包裹了map,因为在Python 3 中map 返回一个可迭代对象而不是一个列表。

【讨论】:

  • 这也适用于 Python 2.7 吗?有人告诉我从那开始,所以这就是我目前所处的位置:)
  • 是的,在 Python 2.7 中,用 tuple 包装 map 也可以,虽然会慢一些,因为 tuple 必须将 map 创建的列表转换为元组.
  • 你不需要那个元组包装,zip 处理任何迭代。
  • @PM2Ring:这很公平,但 OP 可能希望稍后重用 capitalsstates。我经常将这种包装作为一种防御性编码。
【解决方案2】:
questions = ['What is the capital of the state %s' %(list[x]) for x in range(50)]

试试这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多