【问题标题】:Python: Iterate two lists, to unify string from column 1 with column 2Python:迭代两个列表,以将第 1 列的字符串与第 2 列统一
【发布时间】:2018-10-24 11:45:27
【问题描述】:

所以我将这个 xlsx 文件导入 Python,其中包含两列。我想统一每一列来制作一个统一的字符串。所以输出应该是一个列,其中第 1 列的字符串与第 2 列的字符串合并。行数将保持不变。下面是我的代码,你可以看到没有什么疯狂的,我正在考虑做一个 for 循环,有什么想法吗?非常感谢!

import xlrd
file_location = "C:/Users/Desktop/manual.xlsx"
workbook = xlrd.open_workbook(file_location)

【问题讨论】:

    标签: python python-3.x list for-loop concatenation


    【解决方案1】:

    所以,有两个列表:

    l1 = ["hi", "there"]
    l2 = [" Jon", " are"]
    

    您可以使用地图例如:

    list(map(lambda x, y: " ".join((x,y)), l1, l2))
    ['hi Jon', 'there are']
    

    【讨论】:

      【解决方案2】:

      如果 xlsx 确实只包含 2 列,那么为什么不将整个文件作为原始文本读取,然后按换行符进行拆分,而不是使用 xlrd 加载工作簿?如果您以这种方式考虑,该文件已经具有“组合”列...

      可以这么简单:

      rows = open("filename").read().splitlines()
      

      【讨论】:

        【解决方案3】:

        使用zip 和列表理解的另一种可能的解决方案,可以说它优于map 以提高可读性:

        >>> a = ['a', 'c']
        >>> b = ['b', 'd']
        >>> [' '.join(row) for row in zip(a, b)]
        ['a b', 'c d']
        

        【讨论】:

          【解决方案4】:

          pandas 很容易做到这一点。以下应该有效(未测试,因为我没有您的数据)。

          import xlrd
          import pandas as pd
          file_location = "C:/Users/Desktop/manual.xlsx"
          workbook = xlrd.open_workbook(file_location)
          
          df = pd.read_excel(workbook)
          df['col3'] = df['col1'].astype(str) + df['col2'].astype(str)
          

          【讨论】:

          • 这似乎是敲钉子的大锤
          • @DemianBrecht 也许吧。我不知道我们在这里获取了多少数据,而且我之前没有使用过xlrd 数据。但是我知道pandas的操作速度很快!该代码在 imo 中也非常易读,因此我认为答案可能会有所帮助。
          猜你喜欢
          • 1970-01-01
          • 2011-10-29
          • 1970-01-01
          • 2021-02-18
          • 2022-01-11
          • 2020-05-24
          • 1970-01-01
          • 2018-10-25
          • 2016-09-22
          相关资源
          最近更新 更多